From f2c00ecced1df96fe81894d19a6b8ec754beedb9 Mon Sep 17 00:00:00 2001 From: renaud dubois Date: Mon, 25 Nov 2024 10:04:00 +0100 Subject: [PATCH] Pushing libMPC: Musig2 --- README.md | 50 +- src/README.md | 85 + src/libMPC/README.md | 185 + src/libMPC/SCL_Musig2.mjs | 474 + src/libMPC/SCL_ecc.mjs | 127 + src/libMPC/bip327.mjs | 579 + src/libMPC/common.mjs | 60 + src/libMPC/node_modules/.DS_Store | Bin 0 -> 6148 bytes src/libMPC/node_modules/.bin/sha.js | 1 + src/libMPC/node_modules/.package-lock.json | 450 + src/libMPC/node_modules/@noble/.DS_Store | Bin 0 -> 8196 bytes src/libMPC/node_modules/@noble/curves/LICENSE | 21 + .../node_modules/@noble/curves/README.md | 1062 ++ .../@noble/curves/_shortw_utils.d.ts | 62 + .../@noble/curves/_shortw_utils.d.ts.map | 1 + .../@noble/curves/_shortw_utils.js | 21 + .../@noble/curves/_shortw_utils.js.map | 1 + .../@noble/curves/abstract/bls.d.ts | 125 + .../@noble/curves/abstract/bls.d.ts.map | 1 + .../@noble/curves/abstract/bls.js | 340 + .../@noble/curves/abstract/bls.js.map | 1 + .../@noble/curves/abstract/curve.d.ts | 83 + .../@noble/curves/abstract/curve.d.ts.map | 1 + .../@noble/curves/abstract/curve.js | 230 + .../@noble/curves/abstract/curve.js.map | 1 + .../@noble/curves/abstract/edwards.d.ts | 101 + .../@noble/curves/abstract/edwards.d.ts.map | 1 + .../@noble/curves/abstract/edwards.js | 437 + .../@noble/curves/abstract/edwards.js.map | 1 + .../@noble/curves/abstract/hash-to-curve.d.ts | 58 + .../curves/abstract/hash-to-curve.d.ts.map | 1 + .../@noble/curves/abstract/hash-to-curve.js | 182 + .../curves/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/abstract/modular.d.ts | 127 + .../@noble/curves/abstract/modular.d.ts.map | 1 + .../@noble/curves/abstract/modular.js | 450 + .../@noble/curves/abstract/modular.js.map | 1 + .../@noble/curves/abstract/montgomery.d.ts | 26 + .../curves/abstract/montgomery.d.ts.map | 1 + .../@noble/curves/abstract/montgomery.js | 153 + .../@noble/curves/abstract/montgomery.js.map | 1 + .../@noble/curves/abstract/poseidon.d.ts | 30 + .../@noble/curves/abstract/poseidon.d.ts.map | 1 + .../@noble/curves/abstract/poseidon.js | 113 + .../@noble/curves/abstract/poseidon.js.map | 1 + .../@noble/curves/abstract/tower.d.ts | 107 + .../@noble/curves/abstract/tower.d.ts.map | 1 + .../@noble/curves/abstract/tower.js | 498 + .../@noble/curves/abstract/tower.js.map | 1 + .../@noble/curves/abstract/utils.d.ts | 111 + .../@noble/curves/abstract/utils.d.ts.map | 1 + .../@noble/curves/abstract/utils.js | 362 + .../@noble/curves/abstract/utils.js.map | 1 + .../@noble/curves/abstract/weierstrass.d.ts | 258 + .../curves/abstract/weierstrass.d.ts.map | 1 + .../@noble/curves/abstract/weierstrass.js | 1145 ++ .../@noble/curves/abstract/weierstrass.js.map | 1 + .../node_modules/@noble/curves/bls12-381.d.ts | 3 + .../@noble/curves/bls12-381.d.ts.map | 1 + .../node_modules/@noble/curves/bls12-381.js | 705 + .../@noble/curves/bls12-381.js.map | 1 + .../node_modules/@noble/curves/bn254.d.ts | 13 + .../node_modules/@noble/curves/bn254.d.ts.map | 1 + .../node_modules/@noble/curves/bn254.js | 223 + .../node_modules/@noble/curves/bn254.js.map | 1 + .../node_modules/@noble/curves/ed25519.d.ts | 81 + .../@noble/curves/ed25519.d.ts.map | 1 + .../node_modules/@noble/curves/ed25519.js | 449 + .../node_modules/@noble/curves/ed25519.js.map | 1 + .../node_modules/@noble/curves/ed448.d.ts | 67 + .../node_modules/@noble/curves/ed448.d.ts.map | 1 + .../node_modules/@noble/curves/ed448.js | 406 + .../node_modules/@noble/curves/ed448.js.map | 1 + .../@noble/curves/esm/_shortw_utils.d.ts | 62 + .../@noble/curves/esm/_shortw_utils.d.ts.map | 1 + .../@noble/curves/esm/_shortw_utils.js | 17 + .../@noble/curves/esm/_shortw_utils.js.map | 1 + .../@noble/curves/esm/abstract/bls.d.ts | 125 + .../@noble/curves/esm/abstract/bls.d.ts.map | 1 + .../@noble/curves/esm/abstract/bls.js | 337 + .../@noble/curves/esm/abstract/bls.js.map | 1 + .../@noble/curves/esm/abstract/curve.d.ts | 83 + .../@noble/curves/esm/abstract/curve.d.ts.map | 1 + .../@noble/curves/esm/abstract/curve.js | 225 + .../@noble/curves/esm/abstract/curve.js.map | 1 + .../@noble/curves/esm/abstract/edwards.d.ts | 101 + .../curves/esm/abstract/edwards.d.ts.map | 1 + .../@noble/curves/esm/abstract/edwards.js | 434 + .../@noble/curves/esm/abstract/edwards.js.map | 1 + .../curves/esm/abstract/hash-to-curve.d.ts | 58 + .../esm/abstract/hash-to-curve.d.ts.map | 1 + .../curves/esm/abstract/hash-to-curve.js | 175 + .../curves/esm/abstract/hash-to-curve.js.map | 1 + .../@noble/curves/esm/abstract/modular.d.ts | 127 + .../curves/esm/abstract/modular.d.ts.map | 1 + .../@noble/curves/esm/abstract/modular.js | 426 + .../@noble/curves/esm/abstract/modular.js.map | 1 + .../curves/esm/abstract/montgomery.d.ts | 26 + .../curves/esm/abstract/montgomery.d.ts.map | 1 + .../@noble/curves/esm/abstract/montgomery.js | 150 + .../curves/esm/abstract/montgomery.js.map | 1 + .../@noble/curves/esm/abstract/poseidon.d.ts | 30 + .../curves/esm/abstract/poseidon.d.ts.map | 1 + .../@noble/curves/esm/abstract/poseidon.js | 108 + .../curves/esm/abstract/poseidon.js.map | 1 + .../@noble/curves/esm/abstract/tower.d.ts | 107 + .../@noble/curves/esm/abstract/tower.d.ts.map | 1 + .../@noble/curves/esm/abstract/tower.js | 494 + .../@noble/curves/esm/abstract/tower.js.map | 1 + .../@noble/curves/esm/abstract/utils.d.ts | 111 + .../@noble/curves/esm/abstract/utils.d.ts.map | 1 + .../@noble/curves/esm/abstract/utils.js | 333 + .../@noble/curves/esm/abstract/utils.js.map | 1 + .../curves/esm/abstract/weierstrass.d.ts | 258 + .../curves/esm/abstract/weierstrass.d.ts.map | 1 + .../@noble/curves/esm/abstract/weierstrass.js | 1138 ++ .../curves/esm/abstract/weierstrass.js.map | 1 + .../@noble/curves/esm/bls12-381.d.ts | 3 + .../@noble/curves/esm/bls12-381.d.ts.map | 1 + .../@noble/curves/esm/bls12-381.js | 702 + .../@noble/curves/esm/bls12-381.js.map | 1 + .../node_modules/@noble/curves/esm/bn254.d.ts | 13 + .../@noble/curves/esm/bn254.d.ts.map | 1 + .../node_modules/@noble/curves/esm/bn254.js | 220 + .../@noble/curves/esm/bn254.js.map | 1 + .../@noble/curves/esm/ed25519.d.ts | 81 + .../@noble/curves/esm/ed25519.d.ts.map | 1 + .../node_modules/@noble/curves/esm/ed25519.js | 443 + .../@noble/curves/esm/ed25519.js.map | 1 + .../node_modules/@noble/curves/esm/ed448.d.ts | 67 + .../@noble/curves/esm/ed448.d.ts.map | 1 + .../node_modules/@noble/curves/esm/ed448.js | 401 + .../@noble/curves/esm/ed448.js.map | 1 + .../node_modules/@noble/curves/esm/index.d.ts | 2 + .../@noble/curves/esm/index.d.ts.map | 1 + .../node_modules/@noble/curves/esm/index.js | 3 + .../@noble/curves/esm/index.js.map | 1 + .../@noble/curves/esm/jubjub.d.ts | 9 + .../@noble/curves/esm/jubjub.d.ts.map | 1 + .../node_modules/@noble/curves/esm/jubjub.js | 60 + .../@noble/curves/esm/jubjub.js.map | 1 + .../node_modules/@noble/curves/esm/p256.d.ts | 105 + .../@noble/curves/esm/p256.d.ts.map | 1 + .../node_modules/@noble/curves/esm/p256.js | 42 + .../@noble/curves/esm/p256.js.map | 1 + .../node_modules/@noble/curves/esm/p384.d.ts | 105 + .../@noble/curves/esm/p384.d.ts.map | 1 + .../node_modules/@noble/curves/esm/p384.js | 46 + .../@noble/curves/esm/p384.js.map | 1 + .../node_modules/@noble/curves/esm/p521.d.ts | 105 + .../@noble/curves/esm/p521.d.ts.map | 1 + .../node_modules/@noble/curves/esm/p521.js | 53 + .../@noble/curves/esm/p521.js.map | 1 + .../@noble/curves/esm/package.json | 4 + .../node_modules/@noble/curves/esm/pasta.d.ts | 5 + .../@noble/curves/esm/pasta.d.ts.map | 1 + .../node_modules/@noble/curves/esm/pasta.js | 30 + .../@noble/curves/esm/pasta.js.map | 1 + .../@noble/curves/esm/secp256k1.d.ts | 99 + .../@noble/curves/esm/secp256k1.d.ts.map | 1 + .../@noble/curves/esm/secp256k1.js | 258 + .../@noble/curves/esm/secp256k1.js.map | 1 + .../node_modules/@noble/curves/index.d.ts | 1 + .../node_modules/@noble/curves/index.d.ts.map | 1 + .../node_modules/@noble/curves/index.js | 3 + .../node_modules/@noble/curves/index.js.map | 1 + .../node_modules/@noble/curves/jubjub.d.ts | 9 + .../@noble/curves/jubjub.d.ts.map | 1 + .../node_modules/@noble/curves/jubjub.js | 65 + .../node_modules/@noble/curves/jubjub.js.map | 1 + .../node_modules/@noble/curves/p256.d.ts | 105 + .../node_modules/@noble/curves/p256.d.ts.map | 1 + src/libMPC/node_modules/@noble/curves/p256.js | 45 + .../node_modules/@noble/curves/p256.js.map | 1 + .../node_modules/@noble/curves/p384.d.ts | 105 + .../node_modules/@noble/curves/p384.d.ts.map | 1 + src/libMPC/node_modules/@noble/curves/p384.js | 49 + .../node_modules/@noble/curves/p384.js.map | 1 + .../node_modules/@noble/curves/p521.d.ts | 105 + .../node_modules/@noble/curves/p521.d.ts.map | 1 + src/libMPC/node_modules/@noble/curves/p521.js | 56 + .../node_modules/@noble/curves/p521.js.map | 1 + .../node_modules/@noble/curves/package.json | 167 + .../node_modules/@noble/curves/pasta.d.ts | 5 + .../node_modules/@noble/curves/pasta.d.ts.map | 1 + .../node_modules/@noble/curves/pasta.js | 33 + .../node_modules/@noble/curves/pasta.js.map | 1 + .../node_modules/@noble/curves/secp256k1.d.ts | 99 + .../@noble/curves/secp256k1.d.ts.map | 1 + .../node_modules/@noble/curves/secp256k1.js | 261 + .../@noble/curves/secp256k1.js.map | 1 + .../@noble/curves/src/_shortw_utils.ts | 20 + .../@noble/curves/src/abstract/bls.ts | 556 + .../@noble/curves/src/abstract/curve.ts | 275 + .../@noble/curves/src/abstract/edwards.ts | 541 + .../curves/src/abstract/hash-to-curve.ts | 233 + .../@noble/curves/src/abstract/modular.ts | 494 + .../@noble/curves/src/abstract/montgomery.ts | 188 + .../@noble/curves/src/abstract/poseidon.ts | 118 + .../@noble/curves/src/abstract/tower.ts | 605 + .../@noble/curves/src/abstract/utils.ts | 368 + .../@noble/curves/src/abstract/weierstrass.ts | 1312 ++ .../@noble/curves/src/bls12-381.ts | 756 + .../node_modules/@noble/curves/src/bn254.ts | 237 + .../node_modules/@noble/curves/src/ed25519.ts | 508 + .../node_modules/@noble/curves/src/ed448.ts | 480 + .../node_modules/@noble/curves/src/index.ts | 1 + .../node_modules/@noble/curves/src/jubjub.ts | 63 + .../node_modules/@noble/curves/src/p256.ts | 48 + .../node_modules/@noble/curves/src/p384.ts | 52 + .../node_modules/@noble/curves/src/p521.ts | 68 + .../@noble/curves/src/package.json | 3 + .../node_modules/@noble/curves/src/pasta.ts | 31 + .../@noble/curves/src/secp256k1.ts | 286 + src/libMPC/node_modules/@noble/hashes/LICENSE | 21 + .../node_modules/@noble/hashes/README.md | 550 + .../node_modules/@noble/hashes/_assert.d.ts | 24 + .../node_modules/@noble/hashes/_assert.js | 50 + .../node_modules/@noble/hashes/_assert.js.map | 1 + .../node_modules/@noble/hashes/_blake.d.ts | 28 + .../node_modules/@noble/hashes/_blake.js | 124 + .../node_modules/@noble/hashes/_blake.js.map | 1 + .../node_modules/@noble/hashes/_md.d.ts | 36 + src/libMPC/node_modules/@noble/hashes/_md.js | 134 + .../node_modules/@noble/hashes/_md.js.map | 1 + .../node_modules/@noble/hashes/_u64.d.ts | 55 + src/libMPC/node_modules/@noble/hashes/_u64.js | 85 + .../node_modules/@noble/hashes/_u64.js.map | 1 + .../node_modules/@noble/hashes/argon2.d.ts | 17 + .../node_modules/@noble/hashes/argon2.js | 303 + .../node_modules/@noble/hashes/argon2.js.map | 1 + .../node_modules/@noble/hashes/blake2b.d.ts | 53 + .../node_modules/@noble/hashes/blake2b.js | 193 + .../node_modules/@noble/hashes/blake2b.js.map | 1 + .../node_modules/@noble/hashes/blake2s.d.ts | 47 + .../node_modules/@noble/hashes/blake2s.js | 124 + .../node_modules/@noble/hashes/blake2s.js.map | 1 + .../node_modules/@noble/hashes/blake3.d.ts | 46 + .../node_modules/@noble/hashes/blake3.js | 244 + .../node_modules/@noble/hashes/blake3.js.map | 1 + .../node_modules/@noble/hashes/crypto.d.ts | 2 + .../node_modules/@noble/hashes/crypto.js | 5 + .../node_modules/@noble/hashes/crypto.js.map | 1 + .../@noble/hashes/cryptoNode.d.ts | 2 + .../node_modules/@noble/hashes/cryptoNode.js | 14 + .../@noble/hashes/cryptoNode.js.map | 1 + .../node_modules/@noble/hashes/eskdf.d.ts | 47 + .../node_modules/@noble/hashes/eskdf.js | 161 + .../node_modules/@noble/hashes/eskdf.js.map | 1 + .../@noble/hashes/esm/_assert.d.ts | 24 + .../@noble/hashes/esm/_assert.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/_assert.js | 42 + .../@noble/hashes/esm/_assert.js.map | 1 + .../@noble/hashes/esm/_blake.d.ts | 28 + .../@noble/hashes/esm/_blake.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/_blake.js | 120 + .../@noble/hashes/esm/_blake.js.map | 1 + .../node_modules/@noble/hashes/esm/_md.d.ts | 36 + .../@noble/hashes/esm/_md.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/_md.js | 128 + .../node_modules/@noble/hashes/esm/_md.js.map | 1 + .../node_modules/@noble/hashes/esm/_u64.d.ts | 55 + .../@noble/hashes/esm/_u64.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/_u64.js | 62 + .../@noble/hashes/esm/_u64.js.map | 1 + .../@noble/hashes/esm/argon2.d.ts | 17 + .../@noble/hashes/esm/argon2.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/argon2.js | 297 + .../@noble/hashes/esm/argon2.js.map | 1 + .../@noble/hashes/esm/blake2b.d.ts | 53 + .../@noble/hashes/esm/blake2b.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/blake2b.js | 189 + .../@noble/hashes/esm/blake2b.js.map | 1 + .../@noble/hashes/esm/blake2s.d.ts | 47 + .../@noble/hashes/esm/blake2s.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/blake2s.js | 119 + .../@noble/hashes/esm/blake2s.js.map | 1 + .../@noble/hashes/esm/blake3.d.ts | 46 + .../@noble/hashes/esm/blake3.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/blake3.js | 240 + .../@noble/hashes/esm/blake3.js.map | 1 + .../@noble/hashes/esm/crypto.d.ts | 2 + .../@noble/hashes/esm/crypto.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/crypto.js | 2 + .../@noble/hashes/esm/crypto.js.map | 1 + .../@noble/hashes/esm/cryptoNode.d.ts | 2 + .../@noble/hashes/esm/cryptoNode.d.ts.map | 1 + .../@noble/hashes/esm/cryptoNode.js | 11 + .../@noble/hashes/esm/cryptoNode.js.map | 1 + .../node_modules/@noble/hashes/esm/eskdf.d.ts | 47 + .../@noble/hashes/esm/eskdf.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/eskdf.js | 155 + .../@noble/hashes/esm/eskdf.js.map | 1 + .../node_modules/@noble/hashes/esm/hkdf.d.ts | 27 + .../@noble/hashes/esm/hkdf.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/hkdf.js | 72 + .../@noble/hashes/esm/hkdf.js.map | 1 + .../node_modules/@noble/hashes/esm/hmac.d.ts | 30 + .../@noble/hashes/esm/hmac.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/hmac.js | 81 + .../@noble/hashes/esm/hmac.js.map | 1 + .../node_modules/@noble/hashes/esm/index.d.ts | 2 + .../@noble/hashes/esm/index.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/index.js | 3 + .../@noble/hashes/esm/index.js.map | 1 + .../@noble/hashes/esm/package.json | 10 + .../@noble/hashes/esm/pbkdf2.d.ts | 16 + .../@noble/hashes/esm/pbkdf2.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/pbkdf2.js | 86 + .../@noble/hashes/esm/pbkdf2.js.map | 1 + .../@noble/hashes/esm/ripemd160.d.ts | 25 + .../@noble/hashes/esm/ripemd160.d.ts.map | 1 + .../@noble/hashes/esm/ripemd160.js | 102 + .../@noble/hashes/esm/ripemd160.js.map | 1 + .../@noble/hashes/esm/scrypt.d.ts | 30 + .../@noble/hashes/esm/scrypt.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/scrypt.js | 226 + .../@noble/hashes/esm/scrypt.js.map | 1 + .../node_modules/@noble/hashes/esm/sha1.d.ts | 26 + .../@noble/hashes/esm/sha1.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/sha1.js | 85 + .../@noble/hashes/esm/sha1.js.map | 1 + .../node_modules/@noble/hashes/esm/sha2.d.ts | 3 + .../@noble/hashes/esm/sha2.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/sha2.js | 4 + .../@noble/hashes/esm/sha2.js.map | 1 + .../@noble/hashes/esm/sha256.d.ts | 37 + .../@noble/hashes/esm/sha256.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/sha256.js | 126 + .../@noble/hashes/esm/sha256.js.map | 1 + .../@noble/hashes/esm/sha3-addons.d.ts | 154 + .../@noble/hashes/esm/sha3-addons.d.ts.map | 1 + .../@noble/hashes/esm/sha3-addons.js | 356 + .../@noble/hashes/esm/sha3-addons.js.map | 1 + .../node_modules/@noble/hashes/esm/sha3.d.ts | 98 + .../@noble/hashes/esm/sha3.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/sha3.js | 214 + .../@noble/hashes/esm/sha3.js.map | 1 + .../@noble/hashes/esm/sha512.d.ts | 124 + .../@noble/hashes/esm/sha512.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/sha512.js | 231 + .../@noble/hashes/esm/sha512.js.map | 1 + .../node_modules/@noble/hashes/esm/utils.d.ts | 96 + .../@noble/hashes/esm/utils.d.ts.map | 1 + .../node_modules/@noble/hashes/esm/utils.js | 191 + .../@noble/hashes/esm/utils.js.map | 1 + .../node_modules/@noble/hashes/hkdf.d.ts | 27 + src/libMPC/node_modules/@noble/hashes/hkdf.js | 78 + .../node_modules/@noble/hashes/hkdf.js.map | 1 + .../node_modules/@noble/hashes/hmac.d.ts | 30 + src/libMPC/node_modules/@noble/hashes/hmac.js | 86 + .../node_modules/@noble/hashes/hmac.js.map | 1 + .../node_modules/@noble/hashes/index.d.ts | 1 + .../node_modules/@noble/hashes/index.js | 3 + .../node_modules/@noble/hashes/index.js.map | 1 + .../node_modules/@noble/hashes/package.json | 158 + .../node_modules/@noble/hashes/pbkdf2.d.ts | 16 + .../node_modules/@noble/hashes/pbkdf2.js | 90 + .../node_modules/@noble/hashes/pbkdf2.js.map | 1 + .../node_modules/@noble/hashes/ripemd160.d.ts | 25 + .../node_modules/@noble/hashes/ripemd160.js | 106 + .../@noble/hashes/ripemd160.js.map | 1 + .../node_modules/@noble/hashes/scrypt.d.ts | 30 + .../node_modules/@noble/hashes/scrypt.js | 230 + .../node_modules/@noble/hashes/scrypt.js.map | 1 + .../node_modules/@noble/hashes/sha1.d.ts | 26 + src/libMPC/node_modules/@noble/hashes/sha1.js | 89 + .../node_modules/@noble/hashes/sha1.js.map | 1 + .../node_modules/@noble/hashes/sha2.d.ts | 3 + src/libMPC/node_modules/@noble/hashes/sha2.js | 13 + .../node_modules/@noble/hashes/sha2.js.map | 1 + .../node_modules/@noble/hashes/sha256.d.ts | 37 + .../node_modules/@noble/hashes/sha256.js | 130 + .../node_modules/@noble/hashes/sha256.js.map | 1 + .../@noble/hashes/sha3-addons.d.ts | 154 + .../node_modules/@noble/hashes/sha3-addons.js | 365 + .../@noble/hashes/sha3-addons.js.map | 1 + .../node_modules/@noble/hashes/sha3.d.ts | 98 + src/libMPC/node_modules/@noble/hashes/sha3.js | 219 + .../node_modules/@noble/hashes/sha3.js.map | 1 + .../node_modules/@noble/hashes/sha512.d.ts | 124 + .../node_modules/@noble/hashes/sha512.js | 238 + .../node_modules/@noble/hashes/sha512.js.map | 1 + .../node_modules/@noble/hashes/src/_assert.ts | 51 + .../node_modules/@noble/hashes/src/_blake.ts | 134 + .../node_modules/@noble/hashes/src/_md.ts | 134 + .../node_modules/@noble/hashes/src/_u64.ts | 77 + .../node_modules/@noble/hashes/src/argon2.ts | 374 + .../node_modules/@noble/hashes/src/blake2b.ts | 205 + .../node_modules/@noble/hashes/src/blake2s.ts | 138 + .../node_modules/@noble/hashes/src/blake3.ts | 268 + .../node_modules/@noble/hashes/src/crypto.ts | 5 + .../@noble/hashes/src/cryptoNode.ts | 11 + .../node_modules/@noble/hashes/src/eskdf.ts | 181 + .../node_modules/@noble/hashes/src/hkdf.ts | 79 + .../node_modules/@noble/hashes/src/hmac.ts | 85 + .../node_modules/@noble/hashes/src/index.ts | 1 + .../node_modules/@noble/hashes/src/pbkdf2.ts | 97 + .../@noble/hashes/src/ripemd160.ts | 108 + .../node_modules/@noble/hashes/src/scrypt.ts | 242 + .../node_modules/@noble/hashes/src/sha1.ts | 85 + .../node_modules/@noble/hashes/src/sha2.ts | 3 + .../node_modules/@noble/hashes/src/sha256.ts | 132 + .../@noble/hashes/src/sha3-addons.ts | 423 + .../node_modules/@noble/hashes/src/sha3.ts | 229 + .../node_modules/@noble/hashes/src/sha512.ts | 246 + .../node_modules/@noble/hashes/src/utils.ts | 260 + .../node_modules/@noble/hashes/utils.d.ts | 96 + .../node_modules/@noble/hashes/utils.js | 215 + .../node_modules/@noble/hashes/utils.js.map | 1 + .../node_modules/@noble/secp256k1/LICENSE | 21 + .../node_modules/@noble/secp256k1/README.md | 352 + .../node_modules/@noble/secp256k1/index.d.ts | 98 + .../node_modules/@noble/secp256k1/index.js | 517 + .../node_modules/@noble/secp256k1/index.ts | 441 + .../@noble/secp256k1/package.json | 61 + src/libMPC/node_modules/base-x/LICENSE.md | 22 + src/libMPC/node_modules/base-x/README.md | 74 + src/libMPC/node_modules/base-x/package.json | 58 + .../node_modules/base-x/src/cjs/index.cjs | 122 + .../node_modules/base-x/src/cjs/index.d.ts | 9 + .../node_modules/base-x/src/esm/index.js | 120 + src/libMPC/node_modules/bech32/LICENSE | 22 + src/libMPC/node_modules/bech32/README.md | 42 + .../node_modules/bech32/dist/index.d.ts | 18 + src/libMPC/node_modules/bech32/dist/index.js | 170 + src/libMPC/node_modules/bech32/package.json | 50 + src/libMPC/node_modules/bip174/LICENSE | 21 + src/libMPC/node_modules/bip174/README.md | 109 + src/libMPC/node_modules/bip174/package.json | 65 + .../bip174/src/cjs/lib/combiner/index.cjs | 95 + .../cjs/lib/converter/global/globalXpub.cjs | 96 + .../cjs/lib/converter/global/unsignedTx.cjs | 10 + .../bip174/src/cjs/lib/converter/index.cjs | 100 + .../lib/converter/input/finalScriptSig.cjs | 42 + .../converter/input/finalScriptWitness.cjs | 44 + .../lib/converter/input/nonWitnessUtxo.cjs | 41 + .../cjs/lib/converter/input/partialSig.cjs | 79 + .../cjs/lib/converter/input/porCommitment.cjs | 42 + .../cjs/lib/converter/input/sighashType.cjs | 44 + .../src/cjs/lib/converter/input/tapKeySig.cjs | 49 + .../cjs/lib/converter/input/tapLeafScript.cjs | 70 + .../cjs/lib/converter/input/tapMerkleRoot.cjs | 45 + .../cjs/lib/converter/input/tapScriptSig.cjs | 76 + .../cjs/lib/converter/input/witnessUtxo.cjs | 62 + .../src/cjs/lib/converter/output/tapTree.cjs | 80 + .../lib/converter/shared/bip32Derivation.cjs | 98 + .../cjs/lib/converter/shared/checkPubkey.cjs | 33 + .../cjs/lib/converter/shared/redeemScript.cjs | 47 + .../converter/shared/tapBip32Derivation.cjs | 66 + .../lib/converter/shared/tapInternalKey.cjs | 51 + .../lib/converter/shared/witnessScript.cjs | 49 + .../bip174/src/cjs/lib/converter/tools.cjs | 48 + .../bip174/src/cjs/lib/interfaces.cjs | 2 + .../bip174/src/cjs/lib/parser/fromBuffer.cjs | 409 + .../bip174/src/cjs/lib/parser/index.cjs | 7 + .../bip174/src/cjs/lib/parser/toBuffer.cjs | 76 + .../node_modules/bip174/src/cjs/lib/psbt.cjs | 163 + .../bip174/src/cjs/lib/typeFields.cjs | 64 + .../node_modules/bip174/src/cjs/lib/utils.cjs | 152 + .../bip174/src/esm/lib/combiner/index.d.ts | 2 + .../bip174/src/esm/lib/combiner/index.js | 81 + .../esm/lib/converter/global/globalXpub.d.ts | 6 + .../esm/lib/converter/global/globalXpub.js | 79 + .../esm/lib/converter/global/unsignedTx.d.ts | 2 + .../esm/lib/converter/global/unsignedTx.js | 7 + .../bip174/src/esm/lib/converter/index.d.ts | 108 + .../bip174/src/esm/lib/converter/index.js | 63 + .../lib/converter/input/finalScriptSig.d.ts | 6 + .../esm/lib/converter/input/finalScriptSig.js | 25 + .../converter/input/finalScriptWitness.d.ts | 6 + .../lib/converter/input/finalScriptWitness.js | 27 + .../lib/converter/input/nonWitnessUtxo.d.ts | 6 + .../esm/lib/converter/input/nonWitnessUtxo.js | 24 + .../esm/lib/converter/input/partialSig.d.ts | 6 + .../src/esm/lib/converter/input/partialSig.js | 62 + .../lib/converter/input/porCommitment.d.ts | 6 + .../esm/lib/converter/input/porCommitment.js | 25 + .../esm/lib/converter/input/sighashType.d.ts | 6 + .../esm/lib/converter/input/sighashType.js | 27 + .../esm/lib/converter/input/tapKeySig.d.ts | 6 + .../src/esm/lib/converter/input/tapKeySig.js | 29 + .../lib/converter/input/tapLeafScript.d.ts | 6 + .../esm/lib/converter/input/tapLeafScript.js | 53 + .../lib/converter/input/tapMerkleRoot.d.ts | 6 + .../esm/lib/converter/input/tapMerkleRoot.js | 25 + .../esm/lib/converter/input/tapScriptSig.d.ts | 6 + .../esm/lib/converter/input/tapScriptSig.js | 59 + .../esm/lib/converter/input/witnessUtxo.d.ts | 6 + .../esm/lib/converter/input/witnessUtxo.js | 45 + .../src/esm/lib/converter/output/tapTree.d.ts | 6 + .../src/esm/lib/converter/output/tapTree.js | 60 + .../lib/converter/shared/bip32Derivation.d.ts | 8 + .../lib/converter/shared/bip32Derivation.js | 84 + .../esm/lib/converter/shared/checkPubkey.d.ts | 2 + .../esm/lib/converter/shared/checkPubkey.js | 19 + .../lib/converter/shared/redeemScript.d.ts | 8 + .../esm/lib/converter/shared/redeemScript.js | 33 + .../converter/shared/tapBip32Derivation.d.ts | 8 + .../converter/shared/tapBip32Derivation.js | 52 + .../lib/converter/shared/tapInternalKey.d.ts | 8 + .../lib/converter/shared/tapInternalKey.js | 37 + .../lib/converter/shared/witnessScript.d.ts | 8 + .../esm/lib/converter/shared/witnessScript.js | 35 + .../bip174/src/esm/lib/converter/tools.d.ts | 5 + .../bip174/src/esm/lib/converter/tools.js | 32 + .../bip174/src/esm/lib/interfaces.d.ts | 114 + .../bip174/src/esm/lib/interfaces.js | 0 .../bip174/src/esm/lib/parser/fromBuffer.d.ts | 11 + .../bip174/src/esm/lib/parser/fromBuffer.js | 329 + .../bip174/src/esm/lib/parser/index.d.ts | 8 + .../bip174/src/esm/lib/parser/index.js | 2 + .../bip174/src/esm/lib/parser/toBuffer.d.ts | 8 + .../bip174/src/esm/lib/parser/toBuffer.js | 61 + .../node_modules/bip174/src/esm/lib/psbt.d.ts | 26 + .../node_modules/bip174/src/esm/lib/psbt.js | 150 + .../bip174/src/esm/lib/typeFields.d.ts | 33 + .../bip174/src/esm/lib/typeFields.js | 62 + .../bip174/src/esm/lib/utils.d.ts | 13 + .../node_modules/bip174/src/esm/lib/utils.js | 130 + src/libMPC/node_modules/bitcoinjs-lib/LICENSE | 21 + .../node_modules/bitcoinjs-lib/README.md | 209 + .../node_modules/bitcoinjs-lib/package.json | 113 + .../bitcoinjs-lib/src/cjs/address.cjs | 253 + .../bitcoinjs-lib/src/cjs/address.d.ts | 72 + .../bitcoinjs-lib/src/cjs/bip66.cjs | 115 + .../bitcoinjs-lib/src/cjs/bip66.d.ts | 20 + .../bitcoinjs-lib/src/cjs/block.cjs | 268 + .../bitcoinjs-lib/src/cjs/block.d.ts | 29 + .../bitcoinjs-lib/src/cjs/bufferutils.cjs | 207 + .../bitcoinjs-lib/src/cjs/bufferutils.d.ts | 44 + .../bitcoinjs-lib/src/cjs/crypto.cjs | 141 + .../bitcoinjs-lib/src/cjs/crypto.d.ts | 14 + .../bitcoinjs-lib/src/cjs/ecc_lib.cjs | 154 + .../bitcoinjs-lib/src/cjs/ecc_lib.d.ts | 17 + .../bitcoinjs-lib/src/cjs/index.cjs | 103 + .../bitcoinjs-lib/src/cjs/index.d.ts | 19 + .../bitcoinjs-lib/src/cjs/merkle.cjs | 74 + .../bitcoinjs-lib/src/cjs/merkle.d.ts | 9 + .../bitcoinjs-lib/src/cjs/networks.cjs | 71 + .../bitcoinjs-lib/src/cjs/networks.d.ts | 30 + .../bitcoinjs-lib/src/cjs/ops.cjs | 131 + .../bitcoinjs-lib/src/cjs/ops.d.ts | 7 + .../bitcoinjs-lib/src/cjs/payments/bip341.cjs | 192 + .../src/cjs/payments/bip341.d.ts | 68 + .../bitcoinjs-lib/src/cjs/payments/embed.cjs | 97 + .../bitcoinjs-lib/src/cjs/payments/embed.d.ts | 9 + .../bitcoinjs-lib/src/cjs/payments/index.cjs | 69 + .../bitcoinjs-lib/src/cjs/payments/index.d.ts | 47 + .../bitcoinjs-lib/src/cjs/payments/lazy.cjs | 31 + .../bitcoinjs-lib/src/cjs/payments/lazy.d.ts | 2 + .../bitcoinjs-lib/src/cjs/payments/p2ms.cjs | 202 + .../bitcoinjs-lib/src/cjs/payments/p2ms.d.ts | 9 + .../bitcoinjs-lib/src/cjs/payments/p2pk.cjs | 130 + .../bitcoinjs-lib/src/cjs/payments/p2pk.d.ts | 10 + .../bitcoinjs-lib/src/cjs/payments/p2pkh.cjs | 192 + .../bitcoinjs-lib/src/cjs/payments/p2pkh.d.ts | 10 + .../bitcoinjs-lib/src/cjs/payments/p2sh.cjs | 253 + .../bitcoinjs-lib/src/cjs/payments/p2sh.d.ts | 10 + .../bitcoinjs-lib/src/cjs/payments/p2tr.cjs | 348 + .../bitcoinjs-lib/src/cjs/payments/p2tr.d.ts | 10 + .../bitcoinjs-lib/src/cjs/payments/p2wpkh.cjs | 186 + .../src/cjs/payments/p2wpkh.d.ts | 10 + .../bitcoinjs-lib/src/cjs/payments/p2wsh.cjs | 269 + .../bitcoinjs-lib/src/cjs/payments/p2wsh.d.ts | 10 + .../bitcoinjs-lib/src/cjs/psbt.cjs | 1797 +++ .../bitcoinjs-lib/src/cjs/psbt.d.ts | 205 + .../bitcoinjs-lib/src/cjs/psbt/bip371.cjs | 556 + .../bitcoinjs-lib/src/cjs/psbt/bip371.d.ts | 89 + .../bitcoinjs-lib/src/cjs/psbt/psbtutils.cjs | 228 + .../bitcoinjs-lib/src/cjs/psbt/psbtutils.d.ts | 49 + .../bitcoinjs-lib/src/cjs/push_data.cjs | 133 + .../bitcoinjs-lib/src/cjs/push_data.d.ts | 28 + .../bitcoinjs-lib/src/cjs/script.cjs | 261 + .../bitcoinjs-lib/src/cjs/script.d.ts | 41 + .../bitcoinjs-lib/src/cjs/script_number.cjs | 122 + .../bitcoinjs-lib/src/cjs/script_number.d.ts | 18 + .../src/cjs/script_signature.cjs | 123 + .../src/cjs/script_signature.d.ts | 20 + .../bitcoinjs-lib/src/cjs/transaction.cjs | 602 + .../bitcoinjs-lib/src/cjs/transaction.d.ts | 59 + .../bitcoinjs-lib/src/cjs/types.cjs | 147 + .../bitcoinjs-lib/src/cjs/types.d.ts | 45 + .../bitcoinjs-lib/src/esm/address.js | 193 + .../bitcoinjs-lib/src/esm/bip66.js | 110 + .../bitcoinjs-lib/src/esm/block.js | 225 + .../bitcoinjs-lib/src/esm/bufferutils.js | 156 + .../bitcoinjs-lib/src/esm/crypto.js | 89 + .../bitcoinjs-lib/src/esm/ecc_lib.js | 106 + .../bitcoinjs-lib/src/esm/index.js | 12 + .../bitcoinjs-lib/src/esm/merkle.js | 27 + .../bitcoinjs-lib/src/esm/networks.js | 68 + .../node_modules/bitcoinjs-lib/src/esm/ops.js | 127 + .../bitcoinjs-lib/src/esm/payments/bip341.js | 135 + .../bitcoinjs-lib/src/esm/payments/embed.js | 50 + .../bitcoinjs-lib/src/esm/payments/index.js | 11 + .../bitcoinjs-lib/src/esm/payments/lazy.js | 27 + .../bitcoinjs-lib/src/esm/payments/p2ms.js | 149 + .../bitcoinjs-lib/src/esm/payments/p2pk.js | 82 + .../bitcoinjs-lib/src/esm/payments/p2pkh.js | 144 + .../bitcoinjs-lib/src/esm/payments/p2sh.js | 201 + .../bitcoinjs-lib/src/esm/payments/p2tr.js | 301 + .../bitcoinjs-lib/src/esm/payments/p2wpkh.js | 139 + .../bitcoinjs-lib/src/esm/payments/p2wsh.js | 228 + .../bitcoinjs-lib/src/esm/psbt.js | 1721 +++ .../bitcoinjs-lib/src/esm/psbt/bip371.js | 490 + .../bitcoinjs-lib/src/esm/psbt/psbtutils.js | 168 + .../bitcoinjs-lib/src/esm/push_data.js | 77 + .../bitcoinjs-lib/src/esm/script.js | 199 + .../bitcoinjs-lib/src/esm/script_number.js | 74 + .../bitcoinjs-lib/src/esm/script_signature.js | 75 + .../bitcoinjs-lib/src/esm/transaction.js | 545 + .../bitcoinjs-lib/src/esm/types.js | 83 + src/libMPC/node_modules/bs58/LICENSE | 21 + src/libMPC/node_modules/bs58/README.md | 91 + src/libMPC/node_modules/bs58/package.json | 54 + .../node_modules/bs58/src/cjs/index.cjs | 8 + .../node_modules/bs58/src/cjs/index.d.ts | 3 + src/libMPC/node_modules/bs58/src/esm/index.js | 3 + src/libMPC/node_modules/bs58check/LICENSE | 21 + src/libMPC/node_modules/bs58check/README.md | 27 + .../node_modules/bs58check/package.json | 69 + .../node_modules/bs58check/src/cjs/base.cjs | 50 + .../node_modules/bs58check/src/cjs/base.d.ts | 5 + .../node_modules/bs58check/src/cjs/index.cjs | 12 + .../node_modules/bs58check/src/cjs/index.d.ts | 6 + .../node_modules/bs58check/src/esm/base.js | 45 + .../node_modules/bs58check/src/esm/index.js | 8 + src/libMPC/node_modules/cipher-base/.eslintrc | 3 + .../node_modules/cipher-base/.npmignore | 1 + .../node_modules/cipher-base/.travis.yml | 6 + src/libMPC/node_modules/cipher-base/LICENSE | 21 + src/libMPC/node_modules/cipher-base/README.md | 17 + src/libMPC/node_modules/cipher-base/index.js | 99 + .../node_modules/cipher-base/package.json | 32 + src/libMPC/node_modules/cipher-base/test.js | 111 + .../node_modules/create-hash/.travis.yml | 17 + src/libMPC/node_modules/create-hash/LICENSE | 21 + src/libMPC/node_modules/create-hash/README.md | 19 + .../node_modules/create-hash/browser.js | 30 + src/libMPC/node_modules/create-hash/index.js | 1 + src/libMPC/node_modules/create-hash/md5.js | 5 + .../node_modules/create-hash/package.json | 39 + src/libMPC/node_modules/create-hash/test.js | 41 + .../node_modules/data-uri-to-buffer/README.md | 88 + .../data-uri-to-buffer/dist/index.d.ts | 15 + .../data-uri-to-buffer/dist/index.js | 53 + .../data-uri-to-buffer/dist/index.js.map | 1 + .../data-uri-to-buffer/package.json | 62 + .../data-uri-to-buffer/src/index.ts | 68 + src/libMPC/node_modules/ecpair/LICENSE | 21 + src/libMPC/node_modules/ecpair/README.md | 48 + src/libMPC/node_modules/ecpair/package.json | 80 + .../node_modules/ecpair/src/ecpair.d.ts | 49 + src/libMPC/node_modules/ecpair/src/ecpair.js | 136 + src/libMPC/node_modules/ecpair/src/index.d.ts | 1 + src/libMPC/node_modules/ecpair/src/index.js | 16 + .../node_modules/ecpair/src/networks.d.ts | 15 + .../node_modules/ecpair/src/networks.js | 25 + .../node_modules/ecpair/src/testecc.d.ts | 2 + src/libMPC/node_modules/ecpair/src/testecc.js | 153 + src/libMPC/node_modules/ecpair/src/types.d.ts | 6 + src/libMPC/node_modules/ecpair/src/types.js | 28 + src/libMPC/node_modules/fetch-blob/LICENSE | 21 + src/libMPC/node_modules/fetch-blob/README.md | 106 + src/libMPC/node_modules/fetch-blob/file.d.ts | 2 + src/libMPC/node_modules/fetch-blob/file.js | 49 + src/libMPC/node_modules/fetch-blob/from.d.ts | 26 + src/libMPC/node_modules/fetch-blob/from.js | 100 + src/libMPC/node_modules/fetch-blob/index.d.ts | 3 + src/libMPC/node_modules/fetch-blob/index.js | 250 + .../node_modules/fetch-blob/package.json | 56 + .../node_modules/fetch-blob/streams.cjs | 51 + .../formdata-polyfill/FormData.js | 441 + .../node_modules/formdata-polyfill/LICENSE | 21 + .../node_modules/formdata-polyfill/README.md | 145 + .../formdata-polyfill/esm.min.d.ts | 5 + .../node_modules/formdata-polyfill/esm.min.js | 40 + .../formdata-polyfill/formdata-to-blob.js | 39 + .../formdata-polyfill/formdata.min.js | 21 + .../formdata-polyfill/package.json | 50 + src/libMPC/node_modules/hash-base/LICENSE | 21 + src/libMPC/node_modules/hash-base/README.md | 48 + src/libMPC/node_modules/hash-base/index.js | 95 + .../node_modules/hash-base/package.json | 42 + src/libMPC/node_modules/inherits/LICENSE | 16 + src/libMPC/node_modules/inherits/README.md | 42 + src/libMPC/node_modules/inherits/inherits.js | 9 + .../node_modules/inherits/inherits_browser.js | 27 + src/libMPC/node_modules/inherits/package.json | 29 + src/libMPC/node_modules/md5.js/LICENSE | 21 + src/libMPC/node_modules/md5.js/README.md | 29 + src/libMPC/node_modules/md5.js/index.js | 146 + src/libMPC/node_modules/md5.js/package.json | 38 + .../.history/README_20210527203617.md | 2 + .../.history/README_20210527212714.md | 41 + .../.history/README_20210527213345.md | 36 + .../.history/README_20210527213411.md | 36 + .../.history/README_20210527213803.md | 36 + .../.history/README_20210527214323.md | 38 + .../.history/README_20210527214408.md | 38 + .../.history/index_20210527203842.js | 0 .../.history/index_20210527203947.js | 8 + .../.history/index_20210527204259.js | 9 + .../.history/index_20210527204418.js | 9 + .../.history/index_20210527204756.js | 11 + .../.history/index_20210527204833.js | 11 + .../.history/index_20210527211208.js | 15 + .../.history/index_20210527211248.js | 15 + .../.history/index_20210527212722.js | 23 + .../.history/index_20210527212731.js | 23 + .../.history/index_20210527212746.js | 15 + .../.history/index_20210527212900.js | 16 + .../.history/index_20210527213022.js | 16 + .../.history/index_20210527213822.js | 16 + .../.history/index_20210527213843.js | 17 + .../.history/index_20210527213852.js | 17 + .../.history/index_20210527213910.js | 16 + .../.history/index_20210527214034.js | 16 + .../.history/index_20210527214643.js | 41 + .../.history/index_20210527214654.js | 41 + .../.history/index_20210527214700.js | 16 + .../.history/package_20210527203733.json | 19 + .../.history/package_20210527203825.json | 16 + .../.history/package_20210527204621.json | 19 + .../.history/package_20210527204913.json | 25 + .../.history/package_20210527204925.json | 25 + .../.history/package_20210527205145.json | 29 + .../.history/package_20210527205156.json | 29 + .../.history/test_20210527205603.js | 0 .../.history/test_20210527205957.js | 3 + .../.history/test_20210527210021.js | 3 + .../node_modules/node-domexception/LICENSE | 21 + .../node_modules/node-domexception/README.md | 46 + .../node_modules/node-domexception/index.js | 16 + .../node-domexception/package.json | 29 + .../node_modules/node-fetch/@types/index.d.ts | 219 + src/libMPC/node_modules/node-fetch/LICENSE.md | 22 + src/libMPC/node_modules/node-fetch/README.md | 872 ++ .../node_modules/node-fetch/package.json | 131 + .../node_modules/node-fetch/src/body.js | 397 + .../node-fetch/src/errors/abort-error.js | 10 + .../node-fetch/src/errors/base.js | 17 + .../node-fetch/src/errors/fetch-error.js | 26 + .../node_modules/node-fetch/src/headers.js | 267 + .../node_modules/node-fetch/src/index.js | 417 + .../node_modules/node-fetch/src/request.js | 313 + .../node_modules/node-fetch/src/response.js | 160 + .../node-fetch/src/utils/get-search.js | 9 + .../node-fetch/src/utils/is-redirect.js | 11 + .../node_modules/node-fetch/src/utils/is.js | 87 + .../node-fetch/src/utils/multipart-parser.js | 432 + .../node-fetch/src/utils/referrer.js | 340 + .../node_modules/randombytes/.travis.yml | 15 + src/libMPC/node_modules/randombytes/.zuul.yml | 1 + src/libMPC/node_modules/randombytes/LICENSE | 21 + src/libMPC/node_modules/randombytes/README.md | 14 + .../node_modules/randombytes/browser.js | 50 + src/libMPC/node_modules/randombytes/index.js | 1 + .../node_modules/randombytes/package.json | 36 + src/libMPC/node_modules/randombytes/test.js | 81 + .../readable-stream/CONTRIBUTING.md | 38 + .../readable-stream/GOVERNANCE.md | 136 + .../node_modules/readable-stream/LICENSE | 47 + .../node_modules/readable-stream/README.md | 106 + .../readable-stream/errors-browser.js | 127 + .../node_modules/readable-stream/errors.js | 116 + .../readable-stream/experimentalWarning.js | 17 + .../readable-stream/lib/_stream_duplex.js | 126 + .../lib/_stream_passthrough.js | 37 + .../readable-stream/lib/_stream_readable.js | 1027 ++ .../readable-stream/lib/_stream_transform.js | 190 + .../readable-stream/lib/_stream_writable.js | 641 + .../lib/internal/streams/async_iterator.js | 180 + .../lib/internal/streams/buffer_list.js | 183 + .../lib/internal/streams/destroy.js | 96 + .../lib/internal/streams/end-of-stream.js | 86 + .../lib/internal/streams/from-browser.js | 3 + .../lib/internal/streams/from.js | 52 + .../lib/internal/streams/pipeline.js | 86 + .../lib/internal/streams/state.js | 22 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + .../node_modules/readable-stream/package.json | 68 + .../readable-stream/readable-browser.js | 9 + .../node_modules/readable-stream/readable.js | 16 + .../node_modules/ripemd160/CHANGELOG.md | 72 + src/libMPC/node_modules/ripemd160/LICENSE | 21 + src/libMPC/node_modules/ripemd160/README.md | 27 + src/libMPC/node_modules/ripemd160/index.js | 163 + .../node_modules/ripemd160/package.json | 37 + src/libMPC/node_modules/safe-buffer/LICENSE | 21 + src/libMPC/node_modules/safe-buffer/README.md | 584 + .../node_modules/safe-buffer/index.d.ts | 187 + src/libMPC/node_modules/safe-buffer/index.js | 65 + .../node_modules/safe-buffer/package.json | 51 + src/libMPC/node_modules/sha.js/.travis.yml | 17 + src/libMPC/node_modules/sha.js/LICENSE | 49 + src/libMPC/node_modules/sha.js/README.md | 44 + src/libMPC/node_modules/sha.js/bin.js | 41 + src/libMPC/node_modules/sha.js/hash.js | 81 + src/libMPC/node_modules/sha.js/index.js | 15 + src/libMPC/node_modules/sha.js/package.json | 30 + src/libMPC/node_modules/sha.js/sha.js | 94 + src/libMPC/node_modules/sha.js/sha1.js | 99 + src/libMPC/node_modules/sha.js/sha224.js | 53 + src/libMPC/node_modules/sha.js/sha256.js | 135 + src/libMPC/node_modules/sha.js/sha384.js | 57 + src/libMPC/node_modules/sha.js/sha512.js | 260 + src/libMPC/node_modules/sha.js/test/hash.js | 75 + src/libMPC/node_modules/sha.js/test/test.js | 100 + .../node_modules/sha.js/test/vectors.js | 72 + .../node_modules/string_decoder/LICENSE | 48 + .../node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 296 + .../node_modules/string_decoder/package.json | 34 + .../node_modules/tiny-secp256k1/LICENSE | 21 + .../node_modules/tiny-secp256k1/README.md | 355 + .../tiny-secp256k1/lib/cjs/index.cjs | 387 + .../tiny-secp256k1/lib/cjs/rand.browser.cjs | 20 + .../tiny-secp256k1/lib/cjs/rand.cjs | 8 + .../tiny-secp256k1/lib/cjs/validate.cjs | 144 + .../tiny-secp256k1/lib/cjs/validate_error.cjs | 26 + .../lib/cjs/wasm_loader.browser.cjs | 7 + .../tiny-secp256k1/lib/cjs/wasm_loader.cjs | 14 + .../tiny-secp256k1/lib/cjs/wasm_path_cjs.cjs | 12 + .../tiny-secp256k1/lib/index.d.ts | 33 + .../node_modules/tiny-secp256k1/lib/index.js | 361 + .../tiny-secp256k1/lib/rand.browser.d.ts | 1 + .../tiny-secp256k1/lib/rand.browser.js | 16 + .../node_modules/tiny-secp256k1/lib/rand.d.ts | 1 + .../node_modules/tiny-secp256k1/lib/rand.js | 4 + .../tiny-secp256k1/lib/secp256k1.wasm | Bin 0 -> 163363 bytes .../tiny-secp256k1/lib/validate.d.ts | 25 + .../tiny-secp256k1/lib/validate.js | 124 + .../tiny-secp256k1/lib/validate_error.d.ts | 9 + .../tiny-secp256k1/lib/validate_error.js | 22 + .../lib/wasm_loader.browser.d.ts | 2 + .../tiny-secp256k1/lib/wasm_loader.browser.js | 5 + .../tiny-secp256k1/lib/wasm_loader.d.ts | 41 + .../tiny-secp256k1/lib/wasm_loader.js | 12 + .../tiny-secp256k1/lib/wasm_path.d.ts | 1 + .../tiny-secp256k1/lib/wasm_path.js | 5 + .../node_modules/uint8array-tools/LICENSE | 21 + .../node_modules/uint8array-tools/README.md | 23 + .../uint8array-tools/package.json | 64 + .../uint8array-tools/src/cjs/browser.cjs | 69 + .../uint8array-tools/src/cjs/index.cjs | 15 + .../uint8array-tools/src/cjs/index.d.ts | 4 + .../uint8array-tools/src/mjs/browser.js | 63 + .../uint8array-tools/src/mjs/index.js | 9 + .../node_modules/tiny-secp256k1/package.json | 64 + src/libMPC/node_modules/typeforce/LICENSE | 21 + src/libMPC/node_modules/typeforce/README.md | 149 + src/libMPC/node_modules/typeforce/async.js | 17 + src/libMPC/node_modules/typeforce/errors.js | 110 + src/libMPC/node_modules/typeforce/extra.js | 91 + src/libMPC/node_modules/typeforce/index.js | 260 + src/libMPC/node_modules/typeforce/native.js | 21 + src/libMPC/node_modules/typeforce/nothrow.js | 12 + .../node_modules/typeforce/package.json | 44 + .../node_modules/uint8array-tools/LICENSE | 21 + .../node_modules/uint8array-tools/README.md | 40 + .../uint8array-tools/package.json | 66 + .../uint8array-tools/src/cjs/browser.cjs | 429 + .../uint8array-tools/src/cjs/index.cjs | 254 + .../uint8array-tools/src/cjs/index.d.ts | 26 + .../uint8array-tools/src/mjs/browser.js | 402 + .../uint8array-tools/src/mjs/index.js | 227 + .../node_modules/util-deprecate/History.md | 16 + .../node_modules/util-deprecate/LICENSE | 24 + .../node_modules/util-deprecate/README.md | 53 + .../node_modules/util-deprecate/browser.js | 67 + .../node_modules/util-deprecate/node.js | 6 + .../node_modules/util-deprecate/package.json | 27 + src/libMPC/node_modules/valibot/LICENSE.md | 9 + src/libMPC/node_modules/valibot/README.md | 79 + .../node_modules/valibot/dist/index.cjs | 5958 ++++++++ .../node_modules/valibot/dist/index.d.cts | 12416 ++++++++++++++++ .../node_modules/valibot/dist/index.d.ts | 12416 ++++++++++++++++ src/libMPC/node_modules/valibot/dist/index.js | 5697 +++++++ .../node_modules/valibot/dist/index.min.cjs | 1 + .../node_modules/valibot/dist/index.min.js | 1 + src/libMPC/node_modules/valibot/package.json | 82 + .../node_modules/varuint-bitcoin/LICENSE | 24 + .../node_modules/varuint-bitcoin/README.md | 21 + .../node_modules/uint8array-tools/LICENSE | 21 + .../node_modules/uint8array-tools/README.md | 40 + .../uint8array-tools/package.json | 66 + .../uint8array-tools/src/cjs/browser.cjs | 261 + .../uint8array-tools/src/cjs/index.cjs | 142 + .../uint8array-tools/src/cjs/index.d.ts | 18 + .../uint8array-tools/src/mjs/browser.js | 242 + .../uint8array-tools/src/mjs/index.js | 123 + .../node_modules/varuint-bitcoin/package.json | 51 + .../varuint-bitcoin/src/cjs/index.cjs | 115 + .../varuint-bitcoin/src/cjs/index.d.ts | 10 + .../varuint-bitcoin/src/esm/index.js | 88 + .../node_modules/web-streams-polyfill/LICENSE | 22 + .../web-streams-polyfill/README.md | 110 + .../dist/polyfill.es2018.js | 4765 ++++++ .../dist/polyfill.es2018.js.map | 1 + .../dist/polyfill.es2018.min.js | 9 + .../dist/polyfill.es2018.min.js.map | 1 + .../dist/polyfill.es2018.mjs | 4745 ++++++ .../dist/polyfill.es2018.mjs.map | 1 + .../web-streams-polyfill/dist/polyfill.es6.js | 4838 ++++++ .../dist/polyfill.es6.js.map | 1 + .../dist/polyfill.es6.min.js | 9 + .../dist/polyfill.es6.min.js.map | 1 + .../dist/polyfill.es6.mjs | 4818 ++++++ .../dist/polyfill.es6.mjs.map | 1 + .../web-streams-polyfill/dist/polyfill.js | 5011 +++++++ .../web-streams-polyfill/dist/polyfill.js.map | 1 + .../web-streams-polyfill/dist/polyfill.min.js | 9 + .../dist/polyfill.min.js.map | 1 + .../web-streams-polyfill/dist/polyfill.mjs | 4991 +++++++ .../dist/polyfill.mjs.map | 1 + .../dist/ponyfill.es2018.js | 4737 ++++++ .../dist/ponyfill.es2018.js.map | 1 + .../dist/ponyfill.es2018.mjs | 4717 ++++++ .../dist/ponyfill.es2018.mjs.map | 1 + .../web-streams-polyfill/dist/ponyfill.es6.js | 4810 ++++++ .../dist/ponyfill.es6.js.map | 1 + .../dist/ponyfill.es6.mjs | 4790 ++++++ .../dist/ponyfill.es6.mjs.map | 1 + .../web-streams-polyfill/dist/ponyfill.js | 4983 +++++++ .../web-streams-polyfill/dist/ponyfill.js.map | 1 + .../web-streams-polyfill/dist/ponyfill.mjs | 4963 ++++++ .../dist/ponyfill.mjs.map | 1 + .../dist/types/polyfill.d.ts | 24 + .../dist/types/ponyfill.d.ts | 780 + .../dist/types/ts3.6/polyfill.d.ts | 28 + .../dist/types/ts3.6/ponyfill.d.ts | 821 + .../dist/types/tsdoc-metadata.json | 11 + .../web-streams-polyfill/es2018/package.json | 14 + .../web-streams-polyfill/es6/package.json | 14 + .../web-streams-polyfill/package.json | 83 + .../ponyfill/es2018/package.json | 13 + .../ponyfill/es6/package.json | 13 + .../ponyfill/package.json | 13 + src/libMPC/node_modules/wif/.npmignore | 2 + src/libMPC/node_modules/wif/.travis.yml | 15 + src/libMPC/node_modules/wif/LICENSE | 21 + src/libMPC/node_modules/wif/README.md | 32 + src/libMPC/node_modules/wif/index.js | 63 + .../wif/node_modules/base-x/LICENSE.md | 22 + .../wif/node_modules/base-x/README.md | 67 + .../wif/node_modules/base-x/package.json | 49 + .../wif/node_modules/base-x/src/index.d.ts | 10 + .../wif/node_modules/base-x/src/index.js | 119 + .../wif/node_modules/bs58/CHANGELOG.md | 61 + .../wif/node_modules/bs58/README.md | 71 + .../wif/node_modules/bs58/index.js | 4 + .../wif/node_modules/bs58/package.json | 37 + .../wif/node_modules/bs58check/LICENSE | 21 + .../wif/node_modules/bs58check/README.md | 27 + .../wif/node_modules/bs58check/base.js | 50 + .../wif/node_modules/bs58check/index.js | 12 + .../wif/node_modules/bs58check/package.json | 52 + src/libMPC/node_modules/wif/package.json | 43 + .../node_modules/wif/test/fixtures.json | 76 + src/libMPC/node_modules/wif/test/index.js | 42 + src/libMPC/package-lock.json | 460 + src/libMPC/package.json | 10 + src/libMPC/rfc8032.mjs | 12 + src/libMPC/test_Musig2.mjs | 296 + src/libMPC/test_bip327.mjs | 450 + 968 files changed, 180098 insertions(+), 37 deletions(-) create mode 100644 src/README.md create mode 100644 src/libMPC/README.md create mode 100644 src/libMPC/SCL_Musig2.mjs create mode 100644 src/libMPC/SCL_ecc.mjs create mode 100644 src/libMPC/bip327.mjs create mode 100644 src/libMPC/common.mjs create mode 100644 src/libMPC/node_modules/.DS_Store create mode 120000 src/libMPC/node_modules/.bin/sha.js create mode 100644 src/libMPC/node_modules/.package-lock.json create mode 100644 src/libMPC/node_modules/@noble/.DS_Store create mode 100644 src/libMPC/node_modules/@noble/curves/LICENSE create mode 100644 src/libMPC/node_modules/@noble/curves/README.md create mode 100644 src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/_shortw_utils.js create mode 100644 src/libMPC/node_modules/@noble/curves/_shortw_utils.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/bls.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/bls.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/curve.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/curve.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/edwards.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/edwards.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/modular.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/modular.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/montgomery.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/montgomery.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/poseidon.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/poseidon.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/tower.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/tower.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/utils.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/utils.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js create mode 100644 src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/bls12-381.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/bls12-381.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/bls12-381.js create mode 100644 src/libMPC/node_modules/@noble/curves/bls12-381.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/bn254.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/bn254.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/bn254.js create mode 100644 src/libMPC/node_modules/@noble/curves/bn254.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/ed25519.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/ed25519.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/ed25519.js create mode 100644 src/libMPC/node_modules/@noble/curves/ed25519.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/ed448.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/ed448.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/ed448.js create mode 100644 src/libMPC/node_modules/@noble/curves/ed448.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bls12-381.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bls12-381.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bn254.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/bn254.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed25519.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed25519.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed448.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/ed448.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/index.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/index.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/index.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/index.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/jubjub.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/jubjub.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p256.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p256.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p256.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p256.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p384.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p384.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p384.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p384.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p521.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p521.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p521.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/p521.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/package.json create mode 100644 src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/pasta.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/pasta.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/esm/secp256k1.js create mode 100644 src/libMPC/node_modules/@noble/curves/esm/secp256k1.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/index.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/index.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/index.js create mode 100644 src/libMPC/node_modules/@noble/curves/index.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/jubjub.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/jubjub.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/jubjub.js create mode 100644 src/libMPC/node_modules/@noble/curves/jubjub.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/p256.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/p256.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/p256.js create mode 100644 src/libMPC/node_modules/@noble/curves/p256.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/p384.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/p384.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/p384.js create mode 100644 src/libMPC/node_modules/@noble/curves/p384.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/p521.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/p521.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/p521.js create mode 100644 src/libMPC/node_modules/@noble/curves/p521.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/package.json create mode 100644 src/libMPC/node_modules/@noble/curves/pasta.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/pasta.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/pasta.js create mode 100644 src/libMPC/node_modules/@noble/curves/pasta.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/secp256k1.d.ts create mode 100644 src/libMPC/node_modules/@noble/curves/secp256k1.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/curves/secp256k1.js create mode 100644 src/libMPC/node_modules/@noble/curves/secp256k1.js.map create mode 100644 src/libMPC/node_modules/@noble/curves/src/_shortw_utils.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/bls.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/curve.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/edwards.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/hash-to-curve.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/modular.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/montgomery.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/poseidon.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/tower.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/utils.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/abstract/weierstrass.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/bls12-381.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/bn254.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/ed25519.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/ed448.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/index.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/jubjub.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/p256.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/p384.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/p521.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/package.json create mode 100644 src/libMPC/node_modules/@noble/curves/src/pasta.ts create mode 100644 src/libMPC/node_modules/@noble/curves/src/secp256k1.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/LICENSE create mode 100644 src/libMPC/node_modules/@noble/hashes/README.md create mode 100644 src/libMPC/node_modules/@noble/hashes/_assert.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/_assert.js create mode 100644 src/libMPC/node_modules/@noble/hashes/_assert.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/_blake.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/_blake.js create mode 100644 src/libMPC/node_modules/@noble/hashes/_blake.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/_md.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/_md.js create mode 100644 src/libMPC/node_modules/@noble/hashes/_md.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/_u64.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/_u64.js create mode 100644 src/libMPC/node_modules/@noble/hashes/_u64.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/argon2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/argon2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/argon2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2b.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2b.js create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2b.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2s.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2s.js create mode 100644 src/libMPC/node_modules/@noble/hashes/blake2s.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/blake3.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/blake3.js create mode 100644 src/libMPC/node_modules/@noble/hashes/blake3.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/crypto.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/crypto.js create mode 100644 src/libMPC/node_modules/@noble/hashes/crypto.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/cryptoNode.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/cryptoNode.js create mode 100644 src/libMPC/node_modules/@noble/hashes/cryptoNode.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/eskdf.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/eskdf.js create mode 100644 src/libMPC/node_modules/@noble/hashes/eskdf.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_assert.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_assert.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_blake.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_blake.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_md.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_md.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_u64.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/_u64.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/argon2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/argon2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2b.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2b.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2s.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake2s.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake3.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/blake3.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/crypto.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/crypto.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/eskdf.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/eskdf.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hkdf.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hkdf.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hmac.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/hmac.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/index.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/index.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/index.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/index.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/package.json create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/scrypt.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/scrypt.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha1.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha1.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha256.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha256.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha3.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha512.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/sha512.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts.map create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/utils.js create mode 100644 src/libMPC/node_modules/@noble/hashes/esm/utils.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/hkdf.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/hkdf.js create mode 100644 src/libMPC/node_modules/@noble/hashes/hkdf.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/hmac.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/hmac.js create mode 100644 src/libMPC/node_modules/@noble/hashes/hmac.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/index.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/index.js create mode 100644 src/libMPC/node_modules/@noble/hashes/index.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/package.json create mode 100644 src/libMPC/node_modules/@noble/hashes/pbkdf2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/pbkdf2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/pbkdf2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/ripemd160.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/ripemd160.js create mode 100644 src/libMPC/node_modules/@noble/hashes/ripemd160.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/scrypt.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/scrypt.js create mode 100644 src/libMPC/node_modules/@noble/hashes/scrypt.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha1.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha1.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha1.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha2.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha2.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha2.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha256.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha256.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha256.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3-addons.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3-addons.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3-addons.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha3.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/sha512.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/sha512.js create mode 100644 src/libMPC/node_modules/@noble/hashes/sha512.js.map create mode 100644 src/libMPC/node_modules/@noble/hashes/src/_assert.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/_blake.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/_md.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/_u64.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/argon2.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/blake2b.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/blake2s.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/blake3.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/crypto.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/cryptoNode.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/eskdf.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/hkdf.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/hmac.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/index.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/pbkdf2.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/ripemd160.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/scrypt.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha1.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha2.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha256.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha3-addons.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha3.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/sha512.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/src/utils.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/utils.d.ts create mode 100644 src/libMPC/node_modules/@noble/hashes/utils.js create mode 100644 src/libMPC/node_modules/@noble/hashes/utils.js.map create mode 100644 src/libMPC/node_modules/@noble/secp256k1/LICENSE create mode 100644 src/libMPC/node_modules/@noble/secp256k1/README.md create mode 100644 src/libMPC/node_modules/@noble/secp256k1/index.d.ts create mode 100644 src/libMPC/node_modules/@noble/secp256k1/index.js create mode 100644 src/libMPC/node_modules/@noble/secp256k1/index.ts create mode 100644 src/libMPC/node_modules/@noble/secp256k1/package.json create mode 100644 src/libMPC/node_modules/base-x/LICENSE.md create mode 100644 src/libMPC/node_modules/base-x/README.md create mode 100644 src/libMPC/node_modules/base-x/package.json create mode 100644 src/libMPC/node_modules/base-x/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/base-x/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/base-x/src/esm/index.js create mode 100644 src/libMPC/node_modules/bech32/LICENSE create mode 100644 src/libMPC/node_modules/bech32/README.md create mode 100644 src/libMPC/node_modules/bech32/dist/index.d.ts create mode 100644 src/libMPC/node_modules/bech32/dist/index.js create mode 100644 src/libMPC/node_modules/bech32/package.json create mode 100644 src/libMPC/node_modules/bip174/LICENSE create mode 100644 src/libMPC/node_modules/bip174/README.md create mode 100644 src/libMPC/node_modules/bip174/package.json create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/combiner/index.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/globalXpub.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/unsignedTx.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/index.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptSig.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptWitness.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/nonWitnessUtxo.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/partialSig.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/porCommitment.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/sighashType.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapKeySig.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapLeafScript.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapMerkleRoot.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapScriptSig.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/witnessUtxo.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/output/tapTree.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/bip32Derivation.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/checkPubkey.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/redeemScript.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapBip32Derivation.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapInternalKey.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/witnessScript.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/converter/tools.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/interfaces.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/parser/fromBuffer.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/parser/index.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/parser/toBuffer.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/psbt.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/typeFields.cjs create mode 100644 src/libMPC/node_modules/bip174/src/cjs/lib/utils.cjs create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/index.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/index.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/interfaces.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/interfaces.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/index.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/index.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/psbt.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/psbt.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/typeFields.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/typeFields.js create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/utils.d.ts create mode 100644 src/libMPC/node_modules/bip174/src/esm/lib/utils.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/LICENSE create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/README.md create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/package.json create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.cjs create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.d.ts create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/address.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/bip66.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/block.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/bufferutils.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/crypto.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/ecc_lib.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/index.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/merkle.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/networks.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/ops.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/bip341.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/embed.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/index.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/lazy.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2ms.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pk.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pkh.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2sh.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2tr.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wpkh.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wsh.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/bip371.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/psbtutils.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/push_data.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/script.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_number.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_signature.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/transaction.js create mode 100644 src/libMPC/node_modules/bitcoinjs-lib/src/esm/types.js create mode 100644 src/libMPC/node_modules/bs58/LICENSE create mode 100644 src/libMPC/node_modules/bs58/README.md create mode 100644 src/libMPC/node_modules/bs58/package.json create mode 100644 src/libMPC/node_modules/bs58/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/bs58/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/bs58/src/esm/index.js create mode 100644 src/libMPC/node_modules/bs58check/LICENSE create mode 100644 src/libMPC/node_modules/bs58check/README.md create mode 100644 src/libMPC/node_modules/bs58check/package.json create mode 100644 src/libMPC/node_modules/bs58check/src/cjs/base.cjs create mode 100644 src/libMPC/node_modules/bs58check/src/cjs/base.d.ts create mode 100644 src/libMPC/node_modules/bs58check/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/bs58check/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/bs58check/src/esm/base.js create mode 100644 src/libMPC/node_modules/bs58check/src/esm/index.js create mode 100644 src/libMPC/node_modules/cipher-base/.eslintrc create mode 100644 src/libMPC/node_modules/cipher-base/.npmignore create mode 100644 src/libMPC/node_modules/cipher-base/.travis.yml create mode 100644 src/libMPC/node_modules/cipher-base/LICENSE create mode 100644 src/libMPC/node_modules/cipher-base/README.md create mode 100644 src/libMPC/node_modules/cipher-base/index.js create mode 100644 src/libMPC/node_modules/cipher-base/package.json create mode 100644 src/libMPC/node_modules/cipher-base/test.js create mode 100644 src/libMPC/node_modules/create-hash/.travis.yml create mode 100644 src/libMPC/node_modules/create-hash/LICENSE create mode 100644 src/libMPC/node_modules/create-hash/README.md create mode 100644 src/libMPC/node_modules/create-hash/browser.js create mode 100644 src/libMPC/node_modules/create-hash/index.js create mode 100644 src/libMPC/node_modules/create-hash/md5.js create mode 100644 src/libMPC/node_modules/create-hash/package.json create mode 100644 src/libMPC/node_modules/create-hash/test.js create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/README.md create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/dist/index.d.ts create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/dist/index.js create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/dist/index.js.map create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/package.json create mode 100644 src/libMPC/node_modules/data-uri-to-buffer/src/index.ts create mode 100644 src/libMPC/node_modules/ecpair/LICENSE create mode 100644 src/libMPC/node_modules/ecpair/README.md create mode 100644 src/libMPC/node_modules/ecpair/package.json create mode 100644 src/libMPC/node_modules/ecpair/src/ecpair.d.ts create mode 100644 src/libMPC/node_modules/ecpair/src/ecpair.js create mode 100644 src/libMPC/node_modules/ecpair/src/index.d.ts create mode 100644 src/libMPC/node_modules/ecpair/src/index.js create mode 100644 src/libMPC/node_modules/ecpair/src/networks.d.ts create mode 100644 src/libMPC/node_modules/ecpair/src/networks.js create mode 100644 src/libMPC/node_modules/ecpair/src/testecc.d.ts create mode 100644 src/libMPC/node_modules/ecpair/src/testecc.js create mode 100644 src/libMPC/node_modules/ecpair/src/types.d.ts create mode 100644 src/libMPC/node_modules/ecpair/src/types.js create mode 100644 src/libMPC/node_modules/fetch-blob/LICENSE create mode 100644 src/libMPC/node_modules/fetch-blob/README.md create mode 100644 src/libMPC/node_modules/fetch-blob/file.d.ts create mode 100644 src/libMPC/node_modules/fetch-blob/file.js create mode 100644 src/libMPC/node_modules/fetch-blob/from.d.ts create mode 100644 src/libMPC/node_modules/fetch-blob/from.js create mode 100644 src/libMPC/node_modules/fetch-blob/index.d.ts create mode 100644 src/libMPC/node_modules/fetch-blob/index.js create mode 100644 src/libMPC/node_modules/fetch-blob/package.json create mode 100644 src/libMPC/node_modules/fetch-blob/streams.cjs create mode 100644 src/libMPC/node_modules/formdata-polyfill/FormData.js create mode 100644 src/libMPC/node_modules/formdata-polyfill/LICENSE create mode 100644 src/libMPC/node_modules/formdata-polyfill/README.md create mode 100644 src/libMPC/node_modules/formdata-polyfill/esm.min.d.ts create mode 100644 src/libMPC/node_modules/formdata-polyfill/esm.min.js create mode 100644 src/libMPC/node_modules/formdata-polyfill/formdata-to-blob.js create mode 100644 src/libMPC/node_modules/formdata-polyfill/formdata.min.js create mode 100644 src/libMPC/node_modules/formdata-polyfill/package.json create mode 100644 src/libMPC/node_modules/hash-base/LICENSE create mode 100644 src/libMPC/node_modules/hash-base/README.md create mode 100644 src/libMPC/node_modules/hash-base/index.js create mode 100644 src/libMPC/node_modules/hash-base/package.json create mode 100644 src/libMPC/node_modules/inherits/LICENSE create mode 100644 src/libMPC/node_modules/inherits/README.md create mode 100644 src/libMPC/node_modules/inherits/inherits.js create mode 100644 src/libMPC/node_modules/inherits/inherits_browser.js create mode 100644 src/libMPC/node_modules/inherits/package.json create mode 100644 src/libMPC/node_modules/md5.js/LICENSE create mode 100644 src/libMPC/node_modules/md5.js/README.md create mode 100644 src/libMPC/node_modules/md5.js/index.js create mode 100644 src/libMPC/node_modules/md5.js/package.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527203617.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527212714.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527213345.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527213411.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527213803.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527214323.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/README_20210527214408.md create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527203842.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527203947.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527204259.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527204418.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527204756.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527204833.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527211208.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527211248.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527212722.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527212731.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527212746.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527212900.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527213022.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527213822.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527213843.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527213852.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527213910.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527214034.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527214643.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527214654.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/index_20210527214700.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527203733.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527203825.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527204621.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527204913.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527204925.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527205145.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/package_20210527205156.json create mode 100644 src/libMPC/node_modules/node-domexception/.history/test_20210527205603.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/test_20210527205957.js create mode 100644 src/libMPC/node_modules/node-domexception/.history/test_20210527210021.js create mode 100644 src/libMPC/node_modules/node-domexception/LICENSE create mode 100644 src/libMPC/node_modules/node-domexception/README.md create mode 100644 src/libMPC/node_modules/node-domexception/index.js create mode 100644 src/libMPC/node_modules/node-domexception/package.json create mode 100644 src/libMPC/node_modules/node-fetch/@types/index.d.ts create mode 100644 src/libMPC/node_modules/node-fetch/LICENSE.md create mode 100644 src/libMPC/node_modules/node-fetch/README.md create mode 100644 src/libMPC/node_modules/node-fetch/package.json create mode 100644 src/libMPC/node_modules/node-fetch/src/body.js create mode 100644 src/libMPC/node_modules/node-fetch/src/errors/abort-error.js create mode 100644 src/libMPC/node_modules/node-fetch/src/errors/base.js create mode 100644 src/libMPC/node_modules/node-fetch/src/errors/fetch-error.js create mode 100644 src/libMPC/node_modules/node-fetch/src/headers.js create mode 100644 src/libMPC/node_modules/node-fetch/src/index.js create mode 100644 src/libMPC/node_modules/node-fetch/src/request.js create mode 100644 src/libMPC/node_modules/node-fetch/src/response.js create mode 100644 src/libMPC/node_modules/node-fetch/src/utils/get-search.js create mode 100644 src/libMPC/node_modules/node-fetch/src/utils/is-redirect.js create mode 100644 src/libMPC/node_modules/node-fetch/src/utils/is.js create mode 100644 src/libMPC/node_modules/node-fetch/src/utils/multipart-parser.js create mode 100644 src/libMPC/node_modules/node-fetch/src/utils/referrer.js create mode 100644 src/libMPC/node_modules/randombytes/.travis.yml create mode 100644 src/libMPC/node_modules/randombytes/.zuul.yml create mode 100644 src/libMPC/node_modules/randombytes/LICENSE create mode 100644 src/libMPC/node_modules/randombytes/README.md create mode 100644 src/libMPC/node_modules/randombytes/browser.js create mode 100644 src/libMPC/node_modules/randombytes/index.js create mode 100644 src/libMPC/node_modules/randombytes/package.json create mode 100644 src/libMPC/node_modules/randombytes/test.js create mode 100644 src/libMPC/node_modules/readable-stream/CONTRIBUTING.md create mode 100644 src/libMPC/node_modules/readable-stream/GOVERNANCE.md create mode 100644 src/libMPC/node_modules/readable-stream/LICENSE create mode 100644 src/libMPC/node_modules/readable-stream/README.md create mode 100644 src/libMPC/node_modules/readable-stream/errors-browser.js create mode 100644 src/libMPC/node_modules/readable-stream/errors.js create mode 100644 src/libMPC/node_modules/readable-stream/experimentalWarning.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/async_iterator.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/buffer_list.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/end-of-stream.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/from-browser.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/from.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/pipeline.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/state.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 src/libMPC/node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 src/libMPC/node_modules/readable-stream/package.json create mode 100644 src/libMPC/node_modules/readable-stream/readable-browser.js create mode 100644 src/libMPC/node_modules/readable-stream/readable.js create mode 100644 src/libMPC/node_modules/ripemd160/CHANGELOG.md create mode 100644 src/libMPC/node_modules/ripemd160/LICENSE create mode 100644 src/libMPC/node_modules/ripemd160/README.md create mode 100644 src/libMPC/node_modules/ripemd160/index.js create mode 100644 src/libMPC/node_modules/ripemd160/package.json create mode 100644 src/libMPC/node_modules/safe-buffer/LICENSE create mode 100644 src/libMPC/node_modules/safe-buffer/README.md create mode 100644 src/libMPC/node_modules/safe-buffer/index.d.ts create mode 100644 src/libMPC/node_modules/safe-buffer/index.js create mode 100644 src/libMPC/node_modules/safe-buffer/package.json create mode 100644 src/libMPC/node_modules/sha.js/.travis.yml create mode 100644 src/libMPC/node_modules/sha.js/LICENSE create mode 100644 src/libMPC/node_modules/sha.js/README.md create mode 100755 src/libMPC/node_modules/sha.js/bin.js create mode 100644 src/libMPC/node_modules/sha.js/hash.js create mode 100644 src/libMPC/node_modules/sha.js/index.js create mode 100644 src/libMPC/node_modules/sha.js/package.json create mode 100644 src/libMPC/node_modules/sha.js/sha.js create mode 100644 src/libMPC/node_modules/sha.js/sha1.js create mode 100644 src/libMPC/node_modules/sha.js/sha224.js create mode 100644 src/libMPC/node_modules/sha.js/sha256.js create mode 100644 src/libMPC/node_modules/sha.js/sha384.js create mode 100644 src/libMPC/node_modules/sha.js/sha512.js create mode 100644 src/libMPC/node_modules/sha.js/test/hash.js create mode 100644 src/libMPC/node_modules/sha.js/test/test.js create mode 100644 src/libMPC/node_modules/sha.js/test/vectors.js create mode 100644 src/libMPC/node_modules/string_decoder/LICENSE create mode 100644 src/libMPC/node_modules/string_decoder/README.md create mode 100644 src/libMPC/node_modules/string_decoder/lib/string_decoder.js create mode 100644 src/libMPC/node_modules/string_decoder/package.json create mode 100644 src/libMPC/node_modules/tiny-secp256k1/LICENSE create mode 100644 src/libMPC/node_modules/tiny-secp256k1/README.md create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/index.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.browser.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate_error.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.browser.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_path_cjs.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/index.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/index.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/rand.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/rand.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/secp256k1.wasm create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/validate.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/validate.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/LICENSE create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/README.md create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/package.json create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/browser.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/browser.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/index.js create mode 100644 src/libMPC/node_modules/tiny-secp256k1/package.json create mode 100644 src/libMPC/node_modules/typeforce/LICENSE create mode 100644 src/libMPC/node_modules/typeforce/README.md create mode 100644 src/libMPC/node_modules/typeforce/async.js create mode 100644 src/libMPC/node_modules/typeforce/errors.js create mode 100644 src/libMPC/node_modules/typeforce/extra.js create mode 100644 src/libMPC/node_modules/typeforce/index.js create mode 100644 src/libMPC/node_modules/typeforce/native.js create mode 100644 src/libMPC/node_modules/typeforce/nothrow.js create mode 100644 src/libMPC/node_modules/typeforce/package.json create mode 100644 src/libMPC/node_modules/uint8array-tools/LICENSE create mode 100644 src/libMPC/node_modules/uint8array-tools/README.md create mode 100644 src/libMPC/node_modules/uint8array-tools/package.json create mode 100644 src/libMPC/node_modules/uint8array-tools/src/cjs/browser.cjs create mode 100644 src/libMPC/node_modules/uint8array-tools/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/uint8array-tools/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/uint8array-tools/src/mjs/browser.js create mode 100644 src/libMPC/node_modules/uint8array-tools/src/mjs/index.js create mode 100644 src/libMPC/node_modules/util-deprecate/History.md create mode 100644 src/libMPC/node_modules/util-deprecate/LICENSE create mode 100644 src/libMPC/node_modules/util-deprecate/README.md create mode 100644 src/libMPC/node_modules/util-deprecate/browser.js create mode 100644 src/libMPC/node_modules/util-deprecate/node.js create mode 100644 src/libMPC/node_modules/util-deprecate/package.json create mode 100644 src/libMPC/node_modules/valibot/LICENSE.md create mode 100644 src/libMPC/node_modules/valibot/README.md create mode 100644 src/libMPC/node_modules/valibot/dist/index.cjs create mode 100644 src/libMPC/node_modules/valibot/dist/index.d.cts create mode 100644 src/libMPC/node_modules/valibot/dist/index.d.ts create mode 100644 src/libMPC/node_modules/valibot/dist/index.js create mode 100644 src/libMPC/node_modules/valibot/dist/index.min.cjs create mode 100644 src/libMPC/node_modules/valibot/dist/index.min.js create mode 100644 src/libMPC/node_modules/valibot/package.json create mode 100644 src/libMPC/node_modules/varuint-bitcoin/LICENSE create mode 100644 src/libMPC/node_modules/varuint-bitcoin/README.md create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/LICENSE create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/README.md create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/package.json create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/browser.cjs create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/browser.js create mode 100644 src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/index.js create mode 100644 src/libMPC/node_modules/varuint-bitcoin/package.json create mode 100644 src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.cjs create mode 100644 src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.d.ts create mode 100644 src/libMPC/node_modules/varuint-bitcoin/src/esm/index.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/LICENSE create mode 100644 src/libMPC/node_modules/web-streams-polyfill/README.md create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts create mode 100644 src/libMPC/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/es2018/package.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/es6/package.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/package.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/ponyfill/es2018/package.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/ponyfill/es6/package.json create mode 100644 src/libMPC/node_modules/web-streams-polyfill/ponyfill/package.json create mode 100644 src/libMPC/node_modules/wif/.npmignore create mode 100644 src/libMPC/node_modules/wif/.travis.yml create mode 100644 src/libMPC/node_modules/wif/LICENSE create mode 100644 src/libMPC/node_modules/wif/README.md create mode 100644 src/libMPC/node_modules/wif/index.js create mode 100644 src/libMPC/node_modules/wif/node_modules/base-x/LICENSE.md create mode 100644 src/libMPC/node_modules/wif/node_modules/base-x/README.md create mode 100644 src/libMPC/node_modules/wif/node_modules/base-x/package.json create mode 100644 src/libMPC/node_modules/wif/node_modules/base-x/src/index.d.ts create mode 100644 src/libMPC/node_modules/wif/node_modules/base-x/src/index.js create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58/CHANGELOG.md create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58/README.md create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58/index.js create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58/package.json create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58check/LICENSE create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58check/README.md create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58check/base.js create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58check/index.js create mode 100644 src/libMPC/node_modules/wif/node_modules/bs58check/package.json create mode 100644 src/libMPC/node_modules/wif/package.json create mode 100644 src/libMPC/node_modules/wif/test/fixtures.json create mode 100644 src/libMPC/node_modules/wif/test/index.js create mode 100644 src/libMPC/package-lock.json create mode 100644 src/libMPC/package.json create mode 100644 src/libMPC/rfc8032.mjs create mode 100644 src/libMPC/test_Musig2.mjs create mode 100644 src/libMPC/test_bip327.mjs diff --git a/README.md b/README.md index 3ce2e70..bcfcf2b 100644 --- a/README.md +++ b/README.md @@ -2,44 +2,22 @@ A Cryptographic Library for Smooth Blockchain uses. -## Compilation +# Source -Clone the repository, then type `forge test`. (Some troubles are solved running `foundryup` and `forge init --force`) -## Deployment +## Solidity (onchain Contracts) -Run deploy.sh to deploy the code on a target chain. -The values `$RPC` and `$CHAINID` shall be set to the chain ones. -The toy private and public key shall be replaced and funded (current can be used for testnet). +On chain contracts are available [here](./src/README.md). +## Javascript (front code) - -## Benchmarks - - -### Forge results - -The benchmarks are performed by averaging forge results over a loop of 100 tests. Be sure to avoid the use of -via-IR and set foundry.toml correctly to reproduce correct measurements. - -| curve | Function | gas | Comment | File| -|--------:|---------|:--:|:----|:----| -| P256 | SCL_ECDSAB4.verify | 159K | ECDSA using RIP7696 (second opcode) | libSCL_ECDSAb4.sol | -|| | | || - - - -### Onchain results - - -| PR # | Create2 | Mainnets | Testnets | -|--------:|---------|:--:|:----| -|[N/A](https://github.com/rdubois-crypto/FreshCryptoLib/pull/46)| 0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409 | | [Sepolia](https://sepolia.etherscan.io/address/0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409#code) ,[Optimism](https://sepolia.etherscan.io/address/0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409#code) | -|| | | | +Source code for front is available [here](./src/libMPC/README.md). # Audits +## Solidity The results of the completed audits are in the doc/audit folder. @@ -54,22 +32,19 @@ See [here](https://github.com/formal-land/coq-of-solidity/tree/guillaume-claret% We are also grateful to Guido (https://github.com/guidovranken) which notice by its independant (and amazing) Fuzzing work that our weak keys testing was incorrect. -# Curves implementation status - - +## Javascript -| curve | status | branch | Comment | File| -|--------:|---------|:--:|:----|:----| -| P256 | OK | main | ECDSA using RIP7696 (first opcode) | libSCL_7212.sol | -| P256 | OK | main | ECDSA using RIP7696 (second opcode) | libSCL_ECDSAb4.sol | -| Ed25519| OK | main | EDDSA using RIP7696 (first opcode) with isogenies | libSCL_RIP6565.sol || +Code hasn't been audited and is delivered for experiments purposes only. Do not use in production. # Acknowledments The following work has been half-funded by the Ethereum Fundation grant number FY24-1386: * ed25519 solidity (libSCL_RIP6565.sol ) + * Formal Verification is hosted on [Formal Land](https://github.com/formal-land/coq-of-solidity/tree/guillaume-claret%40experiments-verification-mulmuladdX_fullgen_b4/coq/CoqOfSolidity/contracts/scl/mulmuladdX_fullgen_b4) repo. + * libMPC + - SCL_Musig2.mjs -SCL is build by the same team of the previous FCL. As such all previous contributors are credited. +SCL is build by the same team of the previous FCL. # Our work in Production @@ -79,6 +54,7 @@ Prior to SCL implementation, our experimental library FCL is still in production * Cometh Connect: https://github.com/cometh-hq/p256-signer/blob/79d58bc619109a069e212d54a18744d3803731bc/contracts/P256Signer.sol * Metamask Delegation Toolkit https://github.com/MetaMask/delegation-framework/blob/635f717372f58a2b338964ba8e3de4ad285c9a47/src/libraries/P256FCLVerifierLib.sol * Safe : https://github.com/safe-global/safe-modules/tree/main/modules/passkey/contracts/vendor/FCL +* Unruggable Wallet : https://github.com/rdubois-crypto/UnruggableWallet/tree/main/src. A hackathon project using Musig2 as building block for a Wallet immune to hardware trapdoor. ## License diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..3ce2e70 --- /dev/null +++ b/src/README.md @@ -0,0 +1,85 @@ +# SmoothCryptoLib (SCL) +A Cryptographic Library for Smooth Blockchain uses. + + +## Compilation + +Clone the repository, then type `forge test`. (Some troubles are solved running `foundryup` and `forge init --force`) + +## Deployment + +Run deploy.sh to deploy the code on a target chain. +The values `$RPC` and `$CHAINID` shall be set to the chain ones. +The toy private and public key shall be replaced and funded (current can be used for testnet). + + + +## Benchmarks + + +### Forge results + +The benchmarks are performed by averaging forge results over a loop of 100 tests. Be sure to avoid the use of -via-IR and set foundry.toml correctly to reproduce correct measurements. + +| curve | Function | gas | Comment | File| +|--------:|---------|:--:|:----|:----| +| P256 | SCL_ECDSAB4.verify | 159K | ECDSA using RIP7696 (second opcode) | libSCL_ECDSAb4.sol | +|| | | || + + + +### Onchain results + + +| PR # | Create2 | Mainnets | Testnets | +|--------:|---------|:--:|:----| +|[N/A](https://github.com/rdubois-crypto/FreshCryptoLib/pull/46)| 0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409 | | [Sepolia](https://sepolia.etherscan.io/address/0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409#code) ,[Optimism](https://sepolia.etherscan.io/address/0x05eFAC4C53Ec12F11f144d0a0D18Df6dfDf83409#code) | +|| | | | + + + +# Audits + +The results of the completed audits are in the doc/audit folder. + + +| Team | branch | Target |status |Residual risks| +|--------:|---------|:---------|:---------|:--:| +| [CryptoExperts](https://github.com/get-smooth/crypto-lib/tree/main/doc/Audits) | CryptoExperts |P256 | Completed | 0| +| [Veridise](https://github.com/get-smooth/crypto-lib/tree/main/doc/Audits) | Veridise |P256, Ed25519 | Completed | 0 | +| [Formal Land](https://github.com/formal-land/coq-of-solidity/tree/guillaume-claret%40experiments-verification-mulmuladdX_fullgen_b4/coq/CoqOfSolidity/contracts/scl/mulmuladdX_fullgen_b4)| Veridise | RIP7696 | Partial Proving | 0 | + +CryptoExperts and Veridise audits consisted in human auditing of the code. Formal Land conducted a partial formal verification of the code. Due to its mathematical complexity, the perimeter was restricted to ecAddn2, ecDblNeg and scalar extraction. +See [here](https://github.com/formal-land/coq-of-solidity/tree/guillaume-claret%40experiments-verification-mulmuladdX_fullgen_b4/coq/CoqOfSolidity/contracts/scl/mulmuladdX_fullgen_b4) for the coq proof of the library. + +We are also grateful to Guido (https://github.com/guidovranken) which notice by its independant (and amazing) Fuzzing work that our weak keys testing was incorrect. + +# Curves implementation status + + + +| curve | status | branch | Comment | File| +|--------:|---------|:--:|:----|:----| +| P256 | OK | main | ECDSA using RIP7696 (first opcode) | libSCL_7212.sol | +| P256 | OK | main | ECDSA using RIP7696 (second opcode) | libSCL_ECDSAb4.sol | +| Ed25519| OK | main | EDDSA using RIP7696 (first opcode) with isogenies | libSCL_RIP6565.sol || + +# Acknowledments + +The following work has been half-funded by the Ethereum Fundation grant number FY24-1386: + * ed25519 solidity (libSCL_RIP6565.sol ) + +SCL is build by the same team of the previous FCL. As such all previous contributors are credited. + +# Our work in Production + +Prior to SCL implementation, our experimental library FCL is still in production in various environments: + +* Base Smart Wallet: fast onboarding using FCL: https://www.smart-wallet.xyz/, deployed at 0x0BA5ED0c6AA8c49038F819E587E2633c4A9F428a (Base main and Sepolia) +* Cometh Connect: https://github.com/cometh-hq/p256-signer/blob/79d58bc619109a069e212d54a18744d3803731bc/contracts/P256Signer.sol +* Metamask Delegation Toolkit https://github.com/MetaMask/delegation-framework/blob/635f717372f58a2b338964ba8e3de4ad285c9a47/src/libraries/P256FCLVerifierLib.sol +* Safe : https://github.com/safe-global/safe-modules/tree/main/modules/passkey/contracts/vendor/FCL + + +## License +License: This software is licensed under MIT License (see LICENSE FILE at root directory of project). diff --git a/src/libMPC/README.md b/src/libMPC/README.md new file mode 100644 index 0000000..14eb7a8 --- /dev/null +++ b/src/libMPC/README.md @@ -0,0 +1,185 @@ +# SmoothCryptoLib (SCL) +A Cryptographic Library for Smooth Blockchain uses. + +This repository is a private fork of the audited SCL. In addition to SCL generic ECC solidity, +it contains the actual experiments around Musig2 and FROST. + + +## Description + +The aim of the Smooth-LibMPC is to provide an open source implementation of +- Musig2: is a MPC scriptless algorithm, specified in BIP327, it is part of Taproot and enables n out of n signature, +- Atomic Swaps: use adaptator signatures to enable trustless bridges, requires Musig2, +- FROST is a threshold signature scheme (k out of n), which enables governance, without requiring to deploy on chain contract, providing more privacy on the governance. + + +The SmoothMPCLib consists in two parts: +- An onchain solidity verifier, implemented in libSCL_BIP327.sol as part of SCL (Smoo.th Crypto Lib) +- A javascript implementation of signer side to be integrated into any webApp leveraging the targeted protocol. + + +### Implementation status + + + +| Protocol | status | branch | Comment | File| +|--------:|---------|:--:|:----|:----| +| Onchain Verifier | OK | main | | libSCL_BIP327.sol | +| Musig2-secp256k1 | OK | main | | bip327.mjs | +| Musig2-ed25519 | TBD | - | | | +| Atomic Swaps | In progress | - | | SCL_atomic_swaps.mjs | +| Frost| TBD | - | | | +| + + + +## Installation + + +### Javascript (signer) library + +It is necessary to install noble-curves, which the library is based on for the elliptic primitives function. + +`npm install @noble/curves` + +Test of BIP327 can be run typing `node test_bip327.mjs`. +The test includes the BIP327 test vectors, enforcing compatibility of the signer with BTC, and any 4337/7702 integrating the libSCL_BIP327.sol verifier. + +### Compile Solidity lib +Clone the repository, then type `forge test`. (Some troubles are solved running `foundryup` and `forge init --force`). + + +# Performing a Multisignature with libMPC Musig2 + + +A 2 of 2 session is described here. It generalizes identically with larger user set. +We use BIP327 with no tweak. + +Prior to any use, an object of type SCL_Musig2 must be initialized with one of the supported curve. + +``` + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); +``` + + +### Key generation and aggregation + +First, user1 and user2 generates their private key, or import them from seed. +``` + const sk1=secp256k1.utils.randomPrivateKey();//this provides a 32 bytes array + const sk2=secp256k1.utils.randomPrivateKey(); +``` + +Corresponding aggregated key is derived from public keys: +``` + const pubK1=signer.IndividualPubKey_array(sk1); + const pubK2=signer.IndividualPubKey_array(sk2); + + + let aggpk = signer.Key_agg(pubkeys)[0];//here aggpk is a 33 bytes compressed public key + let x_aggpk=aggpk.slice(1,33);//x-only version for noncegen +``` +(of course in practice derivation occurs separately in each signer secure domain) + + +### Signature session + +Assuming user generated their public key according to previous section, they now want to jointly sign a message `msg`. An example session is provided [here](https://github.com/rdubois-crypto/UnruggableWallet/blob/66b84ec4f807919dd443907463318fac0ac1b5f5/src/libMPC/test_bip327.mjs#L290). + +#### Round 1 +In first round, user1 and user2 generates public and secret nonces. Public are shared, secret keep in respective secure domain. + +``` + + const nonce1=signer.Nonce_gen_internal(rand1, sk1, pubK1, x_aggpk, msg, Buffer.from("00000000", 'hex')); + const nonce2=signer.Nonce_gen_internal(rand2, sk2, pubK2, x_aggpk, msg, Buffer.from("00000000", 'hex')); + + let aggnonce = signer.Nonce_agg([nonce1[1].toString('hex'), nonce2[1].toString('hex')]); +``` + +#### Round 2 +In second round, each user computes its partial signature, which are then aggregated and broadcast on chain: + +``` + const tweaks=[]; + const session_ctx=[aggnonce, pubkeys, [], [], msg]; + + let p1=signer.Psign(nonce1[0], sk1, session_ctx); + let p2=signer.Psign(nonce2[0], sk2, session_ctx); + + let psigs=[p1,p2]; + + let res=signer.Partial_sig_agg(psigs, session_ctx); +``` +res is the final results to push onchain. One can check the correctness in front before pushing the results: + +``` + let check=signer.Schnorr_verify(msg, x_aggpk, res); + console.log("check=", check); +``` + +# Performing an atomic swap + +The description doesn't include the timelock on both chains, which cancel the deposits if Alice and Bob didn't succeed in their withdrawal. +Abortion of one of the participant is the only way the protocol shall fail, which is resolved by the timelock condition of withdrawal. +By convention chain1 is the chain with the lowest `chainID`. + + +The sequencing of a Musig2 based atomic swap session is as follow: +- Alice and Bob owns respective key pairs $(sk_a, Q_A)$ and $(sk_b, Q_B)$ +- $P$ is the multisig public key computed with `key_agg`, +- A sends 1 token to AB **on chain 2**, B sends 1 token to AB **on chain 1**, both are timelocked (refund if protocol fails), +- A and B agrees offchain on R1 and R2 using `nonce_gen_internal` and `nonce_agg`. First nonce R1 is used for chain1, second R2 for chain2. Corresponding Alice and Bob secnonces are denoted as rA1, rA2, rB1, rB2. +- A chooses a random tweak t, and computes the tweaked partial signature with `psign` then using t as tweak adaptator: + * Alice signs and broadcast off chain $T=tG$, $s'_A1=(t+ra_1)G+H(R, P, m_1)sk_A$, where $m_1$ is the transaction sending coins from AB to A using `psign_adapt`. t is kept secret by Alice. + * Using the same $t, T$, alice signs and broadcast off chain $s'A2=(t+ra_2)G+H(R, P, m_2)sk_A$ where $m_2$ is the transaction sending coins from AB to B. +- B checks the compliance of $T, s'_A1, s'_A2$ using `atomic_check` +- B signs and broadcast off chain partial signature $s_B1=rb.G+H(P,R,m_1)P_B$ with `psign` +- knowing $t, S_A1, S_B1$ A computes $S_{AB}$ the Musig2 signatures of $m_1$ using `sign_untweak`, and broadcast it **on chain** 1. +- B reads the value $S_{AB}$ on chain 1, learns t, then broadcast **on chain 2** $S_{AB}(m_2)$ using `sign_untweak` on chain 2 to unlock its token. + +Note: the protocol requires to broadcast onchain 4 values (2 locked tokens, then two unlocking signatures). + +### Improving privacy + +- $P_A, P_B$ and $P_{AB}$ might differ on chain 1 and 2. +- Using a zk-proof of Discrete Log, it is possible to use a different curve on chain1 and chain2. + +### Improving security + +The element $t$ shall be as protected as a secret key, to prevent $B$ from stealing $A$ token. In the description, Alice has more duty regarding to the protection of this secret. + + + + +# Product Roadmap + +- Musig2 can be used to provide protection against trappoored hardware [as explained here](https://docs.google.com/presentation/d/10JmRVq9qeoIouLyzIOMcMLnfQQbZlZoSP5eTOyXYUdI/edit#slide=id.g2bf9c14683d_1_265). Using Musig2 with account abstraction, it is possible to have a companion app handling a first key, the hardware wallet a second. +- Atomic swaps enables trustless bridging between non EVM chains. We are gonna use this library to provide trustless bridge with EVM, Starknet and BTC, and later with Cosmos and Solana using the Ed25519 version. +- FROST can be used to make an invisible governance in a Vault application. While SCL passkey module (using 7212) makes traditional single owner invisible, using FROST, it is the Safe itself that can be concealed. + + + + + +# Similar work + +Since the publication of our roadmap, + +## References +https://github.com/BlockstreamResearch/scriptless-scripts/blob/a8b6ff21fc7f4529eabbe639fbff49f047a3579d/md/musig2-adaptorsig.md +https://github.com/BlockstreamResearch/scriptless-scripts/blob/master/md/atomic-swap.md +https://eprint.iacr.org/2021/150.pdf + +# Relation with Prior work + +While ecrecover enables an efficient implementation of Schnorr signatures, there is no trivial way to implement atomic swaps with Solana and Cosmos ecosystems. RIP7696 genericity solves the need for ed25519, avoiding to use complex zk-proof to prove discrete log equivalence. + + +## Acknowledgment + + + +## License +License: This software is licensed under MIT License (see LICENSE FILE at root directory of project). diff --git a/src/libMPC/SCL_Musig2.mjs b/src/libMPC/SCL_Musig2.mjs new file mode 100644 index 0000000..2121276 --- /dev/null +++ b/src/libMPC/SCL_Musig2.mjs @@ -0,0 +1,474 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/********************************************************************************************/ + +import { createHash } from 'crypto'; +import { ed25519 } from '@noble/curves/ed25519'; +import{bytes_xor, int_from_bytes, int_to_bytes} from "./common.mjs"; +import { tagged_hashBTC } from './bip327.mjs'; +import { secp256k1 } from '@noble/curves/secp256k1'; + +import { etc, utils, getPublicKey } from '@noble/secp256k1'; +import{SCL_ecc} from './SCL_ecc.mjs'; + + +// Utility to handle different curves +export class SCL_Musig2 +{ + constructor(curve) { + this.curve = new SCL_ecc(curve); + + if (this.curve.curve === 'secp256k1') { + this.order=secp256k1.CURVE.n; + } else if (this.curve.curve === 'ed25519') { + this.order=ed25519.CURVE.n; + } else { + throw new Error('Unsupported curve'); + } + } + + //return bytes + TagHash(tag, message){ + if (this.curve.curve === 'secp256k1') { + return tagged_hashBTC(tag, message); + } else if (this.curve.curve === 'ed25519') { + return taghash_rfc8032(tag, message); + } else { + throw new Error('Unsupported curve'); + } + } + + //hash the concatenation of public keys + #Hash_keys(pubkeys){ + // Concatenate the list of public keys (byte arrays) + const concatenatedPubkeys = Buffer.concat(pubkeys); + + // Use the tagged_hash function with the specified tag and concatenated public keys + return this.TagHash('KeyAgg list', concatenatedPubkeys); + } + + + //return second public key, in order to implement Musig2* trick + #Get_second_key(pubkeys){ + let u=pubkeys.length; + for(let j =0; jthis.order) return false; + let Q=this.curve.PointDecompress(key_aggCtx[0]); + let P= this.curve.GetBase();//base Point + let g=BigInt('0x1') ; + + + if(is_xonly&& (this.curve.Has_even_y(key_aggCtx[0])==false)){ + Q=Q.negate(); + g=order-g;//n-1 + } + + Q=Q.add(P.multiply(t));//Q=Q+t.P + let gacc_ = (g * key_aggCtx[1] ) % this.order + let tacc_ = (t + g * key_aggCtx[2]) % this.order + + return[Q.toRawBytes(), gacc_, tacc_]; + + } + + Key_agg_and_tweak(pubkeys, tweaks, is_xonly){ + let keyagg_ctx = this.Key_agg(pubkeys);//key_aggCtx prior to tweaks + + if(tweaks.length != is_xonly.length) + { + console.log("wrong length"); + return false; + } + + for(let i=0;i this.order){ + return false; + } + s = (s + s_i) % this.order; + } + let g=BigInt(1); + if(this.curve.Has_even_y(Q)==false) + g= this.order - g;//n-1 + + + s = (s + e * g * tacc) % this.order; + s=Buffer.from(s.toString(16), 'hex'); + let R=this.curve.GetX(sessionV[4]); + + return Buffer.concat([R,s]); + + } + +/********************************************************************************************/ +/* VERIFICATION*/ +/********************************************************************************************/ + Schnorr_verify(msg, pubkey, sig){ + + if(sig.length!=64) { + console.log("bad sig length"); + return false;} + + if(pubkey.length!=32) { + console.log("bad pubkey length"); + return false; + } + + let r = int_from_bytes(sig.slice(0,32)); + let s = int_from_bytes(sig.slice(32,64)); + let RawP= Buffer.concat([ Buffer.from("02",'hex'), pubkey]); + let P=this.curve.PointDecompress(RawP);//extract even public key of coordinates x=pubkey + + let concat=Buffer.concat([sig.slice(0,32),pubkey,msg]); + let e = int_from_bytes(this.TagHash('BIP0340/challenge', concat)) % this.order; + + let sG=(this.curve.GetBase()).multiply(s); + let meP=P.multiply( this.order - e); + + let R =sG.add(meP).toRawBytes();//sG-eP, compressed + if(this.curve.Has_even_y(R)!=true) + return false; + + + R=R.slice(1,33);//prune parity of y + + if(int_from_bytes(R)!=r) + return false; + + return true; + } + + +}//end of class Musig2 + +// Function to compute sha256 hash +export function sha512(data) { + return createHash('sha512').update(data).digest(); + } + + +//look at endianness error +export function taghash_rfc8032(tag, message){ + // Convert the tag to a sha256 hash (as bytes) + const U8tag = Buffer.from(tag, 'utf-8'); + + // Concatenate (encodePacked) tagHash, tagHash, and the message + let encoded = Buffer.concat([U8tag, message]); + + // Compute final sha256 hash + let finalHash = sha512(encoded); + //swap then reduce mod q (damned endians) + finalHash=finalHash.reverse(); + + finalHash= int_from_bytes(finalHash) % ed25519.CURVE.n; + + + return int_to_bytes(finalHash,32); +} + + + +function test_hash8032(){ + console.log("/*************************** "); + console.log("Test test_hash8032:"); + + const curve = 'ed25519'; + const signer = new SCL_Musig2(curve); + + //test vector extracted from example of RFC8032 + let r=Buffer.from("6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac",'hex'); + let KpubC=Buffer.from("fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",'hex'); + let Msg=Buffer.from("af82",'hex'); + const expected=Buffer.from("060ab51a60e3f1ceb60549479b152ae2f4a41d9dd8da0f6c3ef2892d51118e95",'hex'); + + const encoded = Buffer.concat([r, KpubC, Msg]); + + + console.log(":",expected.equals(signer.TagHash('',encoded))); +} + + + diff --git a/src/libMPC/SCL_ecc.mjs b/src/libMPC/SCL_ecc.mjs new file mode 100644 index 0000000..2c16ad1 --- /dev/null +++ b/src/libMPC/SCL_ecc.mjs @@ -0,0 +1,127 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/* Description: A wrapper of ecc functions +/********************************************************************************************/ + + +import { ed25519 } from '@noble/curves/ed25519'; +import { secp256k1 } from '@noble/curves/secp256k1'; + +// Utility to handle different curves +export class SCL_ecc +{ + constructor(curve) { + this.curve = curve; + + if (this.curve === 'secp256k1') { + this.order=secp256k1.CURVE.n; + } else if (this.curve === 'ed25519') { + this.order=ed25519.CURVE.n; + } else { + throw new Error('Unsupported curve'); + } + } + + GetBase(){ + if (this.curve === 'secp256k1') { + return secp256k1.ProjectivePoint.BASE; + } + if (this.curve === 'ed25519') { + + return ed25519.ExtendedPoint.BASE; + } + + throw new Error('Unsupported curve'); + } + + GetZero(){ + if (this.curve === 'secp256k1') { + return secp256k1.ProjectivePoint.ZERO; + } + if (this.curve === 'ed25519') { + return ed25519.ExtendedPoint.ZERO; + } + + throw new Error('Unsupported curve'); + } + + + GetX(bytes_Point){ + if (this.curve === 'secp256k1') { + return bytes_Point.slice(1,33); + } + if (this.curve === 'ed25519') { + bytes_Point[0]=bytes_Point[0]&1; + return bytes_Point; + } + } + + Has_even_y(RawHex_Point){ + if (this.curve === 'secp256k1') { + if(RawHex_Point[0]==0x03) + { + return false; + } + else + return true; + } + if (this.curve === 'ed25519'){ + if( (RawHex_Point[0]&&1)==0x01) + { + return false; + } + else + return true; + } + } + + EqualsX(Point1, Point2){ + + return true; + } + + //compress a point + PointCompress(Point){ + if (this.curve === 'secp256k1') {//expecting a 33 bytes value, first byte is 0x02 or 0x03 according to parity + return Point.toRawBytes(); + } else if (this.curve === 'ed25519') {//expecting a 32 bytes value, msb bit stores parity + return Point.toRawBytes();;(tag, message); + } else { + throw new Error('Unsupported curve'); + } + } + + + PointCompressExt(Point){ + if (this.curve === 'secp256k1') { + if(secp256k1.ProjectivePoint.ZERO.equals(Point)) + return Buffer.from("000000000000000000000000000000000000000000000000000000000000000000",'hex');//infty encoded as "OO" vector of size 33 + } + if (this.curve === 'ed25519') { + if(ed25519.ExtendedPoint.ZERO.equals(Point)) + return Buffer.from("0000000000000000000000000000000000000000000000000000000000000000",'hex');//infty encoded as "OO" vector of size 32 + } + return this.PointCompress(Point); + + } + + PointDecompress(bytePoint){ + if (this.curve === 'secp256k1') {//expecting a 33 bytes value, first byte is 0x02 or 0x03 according to parity + return secp256k1.ProjectivePoint.fromHex(bytePoint); + } else if (this.curve === 'ed25519') {//expecting a 32 bytes value, msb bit stores parity + return ed25519.ExtendedPoint.fromHex(bytePoint);(tag, message); + } else { + throw new Error('Unsupported curve'); + } + } + + +} \ No newline at end of file diff --git a/src/libMPC/bip327.mjs b/src/libMPC/bip327.mjs new file mode 100644 index 0000000..7e0cbb8 --- /dev/null +++ b/src/libMPC/bip327.mjs @@ -0,0 +1,579 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/********************************************************************************************/ +// Use import instead of require in ES modules +import { etc, utils, getPublicKey } from '@noble/secp256k1'; +import { randomBytes } from 'crypto'; // Use Node.js's crypto module + +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js +const {mod, ProjectivePoint} = secp256k1; +const {assertValidity} = ProjectivePoint; + +import { hmac } from '@noble/hashes/hmac'; +import { createHash } from 'crypto'; + + +//TODO: remplace errors by errcodes; + +/********************************************************************************************/ +/* GENERAL FUNCTIONS*/ +/********************************************************************************************/ +// Access Field from secp256k1 +const { Field } = secp256k1; + +// Function to compute sha256 hash +export function sha256(data) { + return createHash('sha256').update(data).digest(); +} + +function bytesToHex(bytes) { + return Buffer.from(bytes).toString('hex'); +} + +// Tagged hash function compliant with BIP327 +// tag: str +// message: bytes +export function tagged_hashBTC(tag, message) { + // Convert the tag to a sha256 hash (as bytes) + const tagHash = sha256(Buffer.from(tag, 'utf-8')); + + // Concatenate (encodePacked) tagHash, tagHash, and the message + const encoded = Buffer.concat([tagHash, tagHash, message]); + + // Compute final sha256 hash + const finalHash = sha256(encoded); + + return finalHash; +} + +function bytes_xor(a,b){ + if (a.length !== b.length) { + throw new Error('Byte arrays must be of the same length'); + } + let c=a; + for(let i=0;isecp256k1.CURVE.n) return false; + let Q=ProjectivePoint.fromHex(key_aggCtx[0]); + let P= secp256k1.ProjectivePoint.BASE;//base Point + let g=BigInt('0x1') ; + + + if(is_xonly&& (has_even_y(key_aggCtx[0])==false)){ + Q=Q.negate(); + g=secp256k1.CURVE.n-g;//n-1 + } + + Q=Q.add(P.multiply(t));//Q=Q+t.P + let gacc_ = (g * key_aggCtx[1] ) % secp256k1.CURVE.n + let tacc_ = (t + g * key_aggCtx[2]) % secp256k1.CURVE.n + + return[Q.toRawBytes(), gacc_, tacc_]; + +} + +export function key_agg_and_tweak(pubkeys, tweaks, is_xonly){ + let keyagg_ctx = key_agg(pubkeys);//key_aggCtx prior to tweaks + + if(tweaks.length != is_xonly.length) + { + console.log("wrong length"); + return false; + } + + for(let i=0;i 0n && candidateKNum < secp256k1.CURVE.n) { + return candidateKNum; + } + + // Update K and V with candidateK if invalid + k = hmac(sha256, k, concatBytes(v, new Uint8Array([0]))); + v = hmac(sha256, k, v); + } +} + + +//Hash to scalar for nonce +//all input are bytes +export function nonce_hash(rand, pk, aggpk, i, msgPrefixed, extraIn) { + // Buffer to concatenate all inputs + let buf =rand; + + // Append all parts to the buffer + + buf = Buffer.concat([buf, new Uint8Array([pk.length])]); // Length of pk (1 byte) + buf = Buffer.concat([buf, pk]); + buf = Buffer.concat([buf, new Uint8Array([aggpk.length])]); // Length of aggpk (1 byte) + buf = Buffer.concat([buf, aggpk]); + buf = Buffer.concat([buf, msgPrefixed]); + let extraInLengthBuffer = Buffer.alloc(4); + extraInLengthBuffer.writeUInt32BE(extraIn.length); + buf = Buffer.concat([buf, extraInLengthBuffer]); // Length of extraIn (4 bytes) + buf = Buffer.concat([buf, extraIn]); + buf = Buffer.concat([buf, new Uint8Array([i])]); // Index i (1 byte) + + // Compute the tagged hash with 'MuSig/nonce' as the tag + const hash = tagged_hashBTC('MuSig/nonce', buf); + + // Return the result as a BigInt + return hash; +} + +//Let m_prefixed = bytes(1, 1) || bytes(8, len(m)) || m +export function prefix_msg(msg){ + + if(msg.length==0) return Buffer.from("00",'hex'); + + let buf=Buffer.from("01",'hex'); + let size = Buffer.alloc(8); + size.writeBigUInt64BE(BigInt(msg.length));// Length of msg (8 bytes) + + buf = Buffer.concat([buf,size, msg]); + + return buf; +} + +//expected format for sk is byte array +//aggpk is optional, compressed over 32 bytes +export function nonce_gen_internal(rand, sk,pk,aggpk, m,extra_in){ + if(sk.length!=0) { + rand=bytes_xor(tagged_hashBTC('MuSig/aux', rand), sk) + } + + let msg_prefixed=prefix_msg(m); + + let k_1 = nonce_hash(rand, pk, aggpk, 0, msg_prefixed, extra_in) + let bk_1 = BigInt(`0x${k_1.toString('hex')}`)% secp256k1.CURVE.n; + + let k_2 = nonce_hash(rand, pk, aggpk, 1, msg_prefixed, extra_in) + let bk_2 = BigInt(`0x${k_2.toString('hex')}`)% secp256k1.CURVE.n; + + if(k_1==0) return false; + if(k_2==0) return false; + + let P= secp256k1.ProjectivePoint.BASE; + let Rs1 = (P.multiply(bk_1)).toRawBytes(); + let Rs2 = (P.multiply(bk_2)).toRawBytes(); + + let pubnonce = Buffer.concat([Rs1, Rs2]); + let secnonce = Buffer.concat([k_1, k_2, pk]); + + return [secnonce, pubnonce]; +} + +//individual nonce generation, use counter instead +export function nonce_gen(sk,pk,aggpk, m,extra_in){ + const rand =randomBytes(32); + + return nonce_gen_internal(rand, sk,pk,aggpk, m,extra_in); + +} + +//this part correspond to the round 1 of Musig: aggregation of individual nonces +//input is a 2 dimensional array of pubnonces of size u, in string format +export function nonce_agg(pubnonces){ + + + let u = pubnonces.length; + let aggnonce = Buffer.alloc(0); + for(let j=1;j<=2;j++){ + let Rj = secp256k1.ProjectivePoint.ZERO;//infinity neutral point + + for(let i=0;isecp256k1.CURVE.n){ + return false; + } + s = (s + s_i) % secp256k1.CURVE.n; + } + let g=BigInt(1); + if(has_even_y(Q)==false) + g=secp256k1.CURVE.n - g;//n-1 + + + s = (s + e * g * tacc) % secp256k1.CURVE.n; + s=Buffer.from(s.toString(16), 'hex'); + let R=xbytes(sessionV[4]); + + return Buffer.concat([R,s]); + +} + +//verify one of the partial signature provided by a participant +export function partial_sig_verify_internal(psig, pubnonce, pk, session_ctx){ + let sessionV=get_session_values(session_ctx);//(Q, gacc, tacc, b, R, e) + let s = int_from_bytes(psig); + let R_s1 = cpoint(pubnonce.slice(0,33)); + let R_s2 = cpoint(pubnonce.slice(33,66)); + + let Re_s_ =R_s1.add(R_s2.multiply(b)); + let Re_s=Re_s_.toRawBytes(); + if(Re_s[0]=0x03){ + Re_s[0]=0x02; + } + Re_s=ProjectivePoint.fromHex(Re_s); + a=key_agg_coeff(session_ctx[1], pk); + let g=BigInt(1); + if(has_even_y(Q)==false) + g=secp256k1.CURVE.n - g;//n-1 + let P=ProjectivePoint.fromHex(pk);//partial input public key + + g=(g*gacc) % secp256k1.CURVE.n; + + let G= secp256k1.ProjectivePoint.BASE; + let P1 = (G.multiply(s)); + let P2=Re_s.add(P.multiply((e*a*g)% secp256k1.CURVE.n)); + + + return (P1==P2); +} + + +/********************************************************************************************/ +/* STANDARD SIGNATURE VERIFICATION FUNCTIONS*/ +/********************************************************************************************/ + +//this is schnorr BIP340, pubkey is x-coordinate only, assuming even y +export function schnorr_verify(msg, pubkey, sig){ + + if(sig.length!=64) { + console.log("bad sig length"); + return false;} + + if(pubkey.length!=32) { + console.log("bad pubkey length"); + return false; + } + + let r = int_from_bytes(sig.slice(0,32)); + let s = int_from_bytes(sig.slice(32,64)); + let RawP= Buffer.concat([ Buffer.from("02",'hex'), pubkey]); + let P=secp256k1.ProjectivePoint.fromHex(RawP);//extract even public key of coordinates x=pubkey + + let concat=Buffer.concat([sig.slice(0,32),pubkey,msg]); + let e = int_from_bytes(tagged_hashBTC('BIP0340/challenge', concat)) % secp256k1.CURVE.n; + + let sG=(secp256k1.ProjectivePoint.BASE).multiply(s); + let meP=P.multiply( secp256k1.CURVE.n - e); + + let R =sG.add(meP).toRawBytes();//sG-eP, compressed + if(has_even_y(R)!=true) + return false; + + + R=R.slice(1,33);//prune parity of y + + if(int_from_bytes(R)!=r) + return false; + + return true; +} + diff --git a/src/libMPC/common.mjs b/src/libMPC/common.mjs new file mode 100644 index 0000000..77f618e --- /dev/null +++ b/src/libMPC/common.mjs @@ -0,0 +1,60 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/********************************************************************************************/ + +export function bytes_xor(a,b){ + if (a.length !== b.length) { + throw new Error('Byte arrays must be of the same length'); + } + let c=a; + for(let i=0;i parseInt(byte, 16))); + + // Pad the result to the desired byte length (if specified) + if (byteLength && bytes.length < byteLength) { + const padding = new Uint8Array(byteLength - bytes.length); + return new Uint8Array([...padding, ...bytes]); + } else if (byteLength && bytes.length > byteLength) { + throw new Error(`BigInt does not fit in ${byteLength} bytes.`); + } + + return Buffer.from(bytes); + } diff --git a/src/libMPC/node_modules/.DS_Store b/src/libMPC/node_modules/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..c649ade3a65f07f14a594f50d92ff63f67763b1e GIT binary patch literal 6148 zcmeHKO-jQ+6rO3TO({Ya3WA$}+k#2y!r~^xdI2N4P^k$C8jP9Jq-IeHxqx2Cdw3q- zo0%+v0e2$yJ(&64?@Z={%nxIXd#lJ{%w&ui&=5H)ErRaWP)8>taydrI;;_sYVJgCw zf&QWkzkQdvEMtO&toi*P;UZ1)!nQwor`y}v?Hhe#Xx#fxqV$WPSmj=@yhZCuh%~JA zAiPfEa&GRQi>wHeEMCfjB#I&B?k341QF>yPMY*i?Rlpb+gSmOMUOQ7~WI2P~J~_LbKc_F5cvD<*pk2zI#v0y1X)Np2UuLPu9>HJN)VYMj05L!e z5CdDrfIbL};g+qNmP-r}13xo>`-24y(bZTflv@XMczwor4-o})d`lo&8eNT*LWqEH zRSKv|xqf1BRStej=eZgyg{qu!IWvr-XRaSFT+R-DOQtjKDx{tmAO@NYbd_o1`F{bw zOzR`RSwa>uKn(md26%7g&pcR^K3l&n56@Z)+5LZ~AKeu056scKA8 literal 0 HcmV?d00001 diff --git a/src/libMPC/node_modules/.bin/sha.js b/src/libMPC/node_modules/.bin/sha.js new file mode 120000 index 0000000..3c76105 --- /dev/null +++ b/src/libMPC/node_modules/.bin/sha.js @@ -0,0 +1 @@ +../sha.js/bin.js \ No newline at end of file diff --git a/src/libMPC/node_modules/.package-lock.json b/src/libMPC/node_modules/.package-lock.json new file mode 100644 index 0000000..476c9f8 --- /dev/null +++ b/src/libMPC/node_modules/.package-lock.json @@ -0,0 +1,450 @@ +{ + "name": "libMPC", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@noble/curves": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.6.0.tgz", + "integrity": "sha512-TlaHRXDehJuRNR9TfZDNQ45mMEd5dwUwmicsafcIX4SsNiqnCHKjE/1alYPd/lDRVhxdhUAlv8uEhMCI5zjIJQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.5.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.5.0.tgz", + "integrity": "sha512-1j6kQFb7QRru7eKN3ZDvRcP13rugwdxZqCjbiAVZfIJwgj2A65UmT4TgARXGlXgnRkORLTDTrO19ZErt7+QXgA==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/secp256k1": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-2.1.0.tgz", + "integrity": "sha512-XLEQQNdablO0XZOIniFQimiXsZDNwaYgL96dZwC54Q30imSbAOFf3NKtepc+cXyuZf5Q1HCgbqgZ2UFFuHVcEw==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/base-x": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.0.tgz", + "integrity": "sha512-sMW3VGSX1QWVFA6l8U62MLKz29rRfpTlYdCqLdpLo1/Yd4zZwSbnUaDfciIAowAqvq7YFnWq9hrhdg1KYgc1lQ==", + "license": "MIT" + }, + "node_modules/bech32": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bech32/-/bech32-2.0.0.tgz", + "integrity": "sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==", + "license": "MIT" + }, + "node_modules/bip174": { + "version": "3.0.0-rc.1", + "resolved": "https://registry.npmjs.org/bip174/-/bip174-3.0.0-rc.1.tgz", + "integrity": "sha512-+8P3BpSairVNF2Nee6Ksdc1etIjWjBOi/MH0MwKtq9YaYp+S2Hk2uvup0e8hCT4IKlS58nXJyyQVmW92zPoD4Q==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.9", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bitcoinjs-lib": { + "version": "7.0.0-rc.0", + "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-7.0.0-rc.0.tgz", + "integrity": "sha512-7CQgOIbREemKR/NT2uc3uO/fkEy+6CM0sLxboVVY6bv6DbZmPt3gg5Y/hhWgQFeZu5lfTbtVAv32MIxf7lMh4g==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bech32": "^2.0.0", + "bip174": "^3.0.0-rc.0", + "bs58check": "^4.0.0", + "uint8array-tools": "^0.0.9", + "valibot": "^0.38.0", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "dependencies": { + "base-x": "^5.0.0" + } + }, + "node_modules/bs58check": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-4.0.0.tgz", + "integrity": "sha512-FsGDOnFg9aVI9erdriULkd/JjEWONV/lQE5aYziB5PoBsXRind56lh8doIZIc9X4HoxT5x4bLjMWN1/NB8Zp5g==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bs58": "^6.0.0" + } + }, + "node_modules/cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ecpair": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ecpair/-/ecpair-2.0.0.tgz", + "integrity": "sha512-5vpYFWxq9V3r/FO33k7SHA1Tl0e4Y5qJiQ3wYGl54o3a7zflNV2U/a5dh8Wmzk5qc3g1OsDPdqBGwRmomvJxoA==", + "license": "MIT", + "dependencies": { + "randombytes": "^2.1.0", + "typeforce": "^1.18.0", + "wif": "^2.0.6" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/hash-base": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", + "integrity": "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "safe-buffer": "^5.2.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "license": "(MIT AND BSD-3-Clause)", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/tiny-secp256k1": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/tiny-secp256k1/-/tiny-secp256k1-2.2.3.tgz", + "integrity": "sha512-SGcL07SxcPN2nGKHTCvRMkQLYPSoeFcvArUSCYtjVARiFAWU44cCIqYS0mYAU6nY7XfvwURuTIGo2Omt3ZQr0Q==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "0.0.7" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tiny-secp256k1/node_modules/uint8array-tools": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.7.tgz", + "integrity": "sha512-vrrNZJiusLWoFWBqz5Y5KMCgP9W9hnjZHzZiZRT8oNAkq3d5Z5Oe76jAvVVSRh4U8GGR90N2X1dWtrhvx6L8UQ==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typeforce": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/typeforce/-/typeforce-1.18.0.tgz", + "integrity": "sha512-7uc1O8h1M1g0rArakJdf0uLRSSgFcYexrVoKo+bzJd32gd4gDy2L/Z+8/FjPnU9ydY3pEnVPtr9FyscYY60K1g==", + "license": "MIT" + }, + "node_modules/uint8array-tools": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.9.tgz", + "integrity": "sha512-9vqDWmoSXOoi+K14zNaf6LBV51Q8MayF0/IiQs3GlygIKUYtog603e6virExkjjFosfJUBI4LhbQK1iq8IG11A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/valibot": { + "version": "0.38.0", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-0.38.0.tgz", + "integrity": "sha512-RCJa0fetnzp+h+KN9BdgYOgtsMAG9bfoJ9JSjIhFHobKWVWyzM3jjaeNTdpFK9tQtf3q1sguXeERJ/LcmdFE7w==", + "license": "MIT", + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/varuint-bitcoin": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/varuint-bitcoin/-/varuint-bitcoin-2.0.0.tgz", + "integrity": "sha512-6QZbU/rHO2ZQYpWFDALCDSRsXbAs1VOEmXAxtbtjLtKuMJ/FQ8YbhfxlaiKv5nklci0M6lZtlZyxo9Q+qNnyog==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.8" + } + }, + "node_modules/varuint-bitcoin/node_modules/uint8array-tools": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.8.tgz", + "integrity": "sha512-xS6+s8e0Xbx++5/0L+yyexukU7pz//Yg6IHg3BKhXotg1JcYtgxVcUctQ0HxLByiJzpAkNFawz1Nz5Xadzo82g==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/wif": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/wif/-/wif-2.0.6.tgz", + "integrity": "sha512-HIanZn1zmduSF+BQhkE+YXIbEiH0xPr1012QbFEGB0xsKqJii0/SqJjyn8dFv6y36kOznMgMB+LGcbZTJ1xACQ==", + "license": "MIT", + "dependencies": { + "bs58check": "<3.0.0" + } + }, + "node_modules/wif/node_modules/base-x": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.10.tgz", + "integrity": "sha512-7d0s06rR9rYaIWHkpfLIFICM/tkSVdoPC9qYAQRpxn9DdKNWNsKC0uk++akckyLq16Tx2WIinnZ6WRriAt6njQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/wif/node_modules/bs58": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz", + "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==", + "license": "MIT", + "dependencies": { + "base-x": "^3.0.2" + } + }, + "node_modules/wif/node_modules/bs58check": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-2.1.2.tgz", + "integrity": "sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==", + "license": "MIT", + "dependencies": { + "bs58": "^4.0.0", + "create-hash": "^1.1.0", + "safe-buffer": "^5.1.2" + } + } + } +} diff --git a/src/libMPC/node_modules/@noble/.DS_Store b/src/libMPC/node_modules/@noble/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..13434d27b95b156cb649dfaad6c1a7eb0ffe179f GIT binary patch literal 8196 zcmeHMU2GIp6h3EKV6IRZe)==ZPgd4Yq^s^$`vZ-zblVC7DR%o0y6)}_bi#C|?9A>W zO|^+JK8X1LrY6M12NF@^3x+2n@#jSiHbkQjMtL$(UNq{P=iWP8{z`Z;{)D;7+;h)8 z=gi%6<~#S!nFRpsE*VLHCIC?B;#6Bo-2#ov`E^}Wf|**PNcI4&&<5>r7?SzQb=u)X z7=bVXVFbbmgb@fM@Lz}ko!PvpH#qmDH0;9&gb}zUBf$5EC|#VU0y-+)g z0*FRqssn^gG@z+~&Ppmw>7KHBz`zuP5(A|<$)jAIXeywyl1g(xX$}~yj6sEhVs)~M z3U$Dgq+uUMAdJBE5#Z^=zylKsFm+}9?oH)wH&490u`H92@RBCD$EncE7QJ1QZ zWG387#?SdBuRB-V&$&U@we!_+EB#h9r0*K=S)00olLZL#-qu^{T(wiOs$XI+cl6qY)?Awv(g(3b_A%q z#=GMSyJmakv~;beq3YV#Ro56>st=Ehj%78i`14oOxNa(1Ca%H|H+&REAxZ`3!B`g}C*xkW!M6h|$x<#SnWCAaUN@-5f# zhRvc!l(Eyx>ep@9*pg`5x;?#f&%U|3+m~xA*eW(o!Et=+pk)@va$do749ht*RIvS!r%9VuD<<6@2VdXyb7=*RDM z4Zez@YVR{4iRn>&KbNG7CiRA@is@$kE;i_qBdV5@ig9)i8$3);m1&-wNwWL&Av>2h zZKfI0teti0BjvzbZMU54Vh`w}1$T0iT=d9;xSUSW%8&Au_vAdkf68>`7w^&g^l@(@ zS2X)81S?hhR9ft!dGU-$!i{;;;?+V4PCOfeIXl=imgq4sXGGa27s< z&){?T0?xx%@Eu%)pWs*c4St6|5b-u_#3qd38oUz|n8a4>!W8bnH1^= z#Dh4278dasPU8$dfzRLz_#(c7ui_i{HlD_J@C<&0=kR0v1i!=|@JGCeKjSZW3I9|S zrCw=NniO4$C^2P|LZAJ3Q>uA0F8OM&bkk^oErIeT*b7>tmblZf);M%_B-eu!_1Xu`B?573>9o#q+)fc^pD|gsojy&8f@TB(rOXkZ&GU zIefJxf%Y96R6@SCC}1}>6T4emEZIm)T%|126v47cBFQM1w3>izX(JXT!?tW?lvP@7 zz;4^lc%o|{_(-HBO?Ubm0DBTn!Mkt<&JkcQz_;){Tq2MHfmFi=0n|0P4mV;mZo?yk(Xn0U5J{^*zS=P4ZWe(WsnEph|K1ya|G(L7LU|a0 zFarPM2w-hbriY*UH`+*ftsSN7F}ir;db5%W6Y97MpBLpg(fL0NX&en?sesN(N)l@S X_=kY%yKH#=U;V-wp8o=mw@UXHHaH!1 literal 0 HcmV?d00001 diff --git a/src/libMPC/node_modules/@noble/curves/LICENSE b/src/libMPC/node_modules/@noble/curves/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/README.md b/src/libMPC/node_modules/@noble/curves/README.md new file mode 100644 index 0000000..3820e98 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/README.md @@ -0,0 +1,1062 @@ +# noble-curves + +Audited & minimal JS implementation of elliptic curve cryptography. + +- 🔒 [**Audited**](#security) by independent security firms +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🏎 Fast: hand-optimized for caveats of JS engines +- 🔍 Reliable: property-based / cross-library / wycheproof tests and fuzzing ensure correctness +- ➰ Short Weierstrass, Edwards, Montgomery curves +- ✍️ ECDSA, EdDSA, Schnorr, BLS signature schemes, ECDH key agreement, hashing to curves +- 🔖 SUF-CMA, SBS (non-repudiation), ZIP215 (consensus friendliness) features for ed25519 +- 🧜‍♂️ Poseidon ZK-friendly hash +- 🪶 190KB (92KB gzipped) for everything with hashes, 22KB (10KB gzipped) for single-curve build + +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-curves/discussions) for questions and support. + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out homepage](https://paulmillr.com/noble/) + for reading resources, documentation and apps built with noble + +## Usage + +> npm install @noble/curves + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available. + +```js +// import * from '@noble/curves'; // Error: use sub-imports, to ensure small app size +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js +// import { secp256k1 } from 'npm:@noble/curves@1.6.0/secp256k1'; // Deno +``` + +- [Implementations](#implementations) + - [ECDSA signatures over secp256k1 and others](#ecdsa-signatures-over-secp256k1-and-others) + - [ECDSA public key recovery & extra entropy](#ecdsa-public-key-recovery--extra-entropy) + - [ECDH: Elliptic Curve Diffie-Hellman](#ecdh-elliptic-curve-diffie-hellman) + - [Schnorr signatures over secp256k1, BIP340](#schnorr-signatures-over-secp256k1-bip340) + - [ed25519, X25519, ristretto255](#ed25519-x25519-ristretto255) + - [ed448, X448, decaf448](#ed448-x448-decaf448) + - [bls12-381](#bls12-381) + - [bn254 aka alt_bn128](#bn254-aka-alt_bn128) + - [Multi-scalar-multiplication](#multi-scalar-multiplication) + - [All available imports](#all-available-imports) + - [Accessing a curve's variables](#accessing-a-curves-variables) +- [Abstract API](#abstract-api) + - [weierstrass: Short Weierstrass curve](#weierstrass-short-weierstrass-curve) + - [edwards: Twisted Edwards curve](#edwards-twisted-edwards-curve) + - [montgomery: Montgomery curve](#montgomery-montgomery-curve) + - [bls: Barreto-Lynn-Scott curves](#bls-barreto-lynn-scott-curves) + - [hash-to-curve: Hashing strings to curve points](#hash-to-curve-hashing-strings-to-curve-points) + - [poseidon: Poseidon hash](#poseidon-poseidon-hash) + - [modular: Modular arithmetics utilities](#modular-modular-arithmetics-utilities) + - [Creating private keys from hashes](#creating-private-keys-from-hashes) + - [utils: Useful utilities](#utils-useful-utilities) +- [Security](#security) +- [Speed](#speed) +- [Upgrading](#upgrading) +- [Contributing & testing](#contributing--testing) +- [Resources](#resources) + +### Implementations + +Implementations use [noble-hashes](https://github.com/paulmillr/noble-hashes). +If you want to use a different hashing library, [abstract API](#abstract-api) doesn't depend on them. + +#### ECDSA signatures over secp256k1 and others + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +// import { p256 } from '@noble/curves/p256'; // or p384 / p521 + +const priv = secp256k1.utils.randomPrivateKey(); +const pub = secp256k1.getPublicKey(priv); +const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa +const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available +const isValid = secp256k1.verify(sig, msg, pub) === true; + +// hex strings are also supported besides Uint8Array-s: +const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'; +const pub2 = secp256k1.getPublicKey(privHex); +``` + +The same code would work for NIST P256 (secp256r1), P384 (secp384r1) & P521 (secp521r1). + +#### ECDSA public key recovery & extra entropy + +```ts +// let sig = secp256k1.Signature.fromCompact(sigHex); // or .fromDER(sigDERHex) +// sig = sig.addRecoveryBit(bit); // bit is not serialized into compact / der format +sig.recoverPublicKey(msg).toRawBytes(); // === pub; // public key recovery + +// extraEntropy https://moderncrypto.org/mail-archive/curves/2017/000925.html +const sigImprovedSecurity = secp256k1.sign(msg, priv, { extraEntropy: true }); +``` + +#### ECDH: Elliptic Curve Diffie-Hellman + +```ts +// 1. The output includes parity byte. Strip it using shared.slice(1) +// 2. The output is not hashed. More secure way is sha256(shared) or hkdf(shared) +const someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey()); +const shared = secp256k1.getSharedSecret(priv, someonesPub); +``` + +#### Schnorr signatures over secp256k1 (BIP340) + +```ts +import { schnorr } from '@noble/curves/secp256k1'; +const priv = schnorr.utils.randomPrivateKey(); +const pub = schnorr.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = schnorr.sign(msg, priv); +const isValid = schnorr.verify(sig, msg, pub); +``` + +#### ed25519, X25519, ristretto255 + +```ts +import { ed25519 } from '@noble/curves/ed25519'; +const priv = ed25519.utils.randomPrivateKey(); +const pub = ed25519.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = ed25519.sign(msg, priv); +ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215 +ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5 +``` + +Default `verify` behavior follows [ZIP215](https://zips.z.cash/zip-0215) and +[can be used in consensus-critical applications](https://hdevalence.ca/blog/2020-10-04-its-25519am). +It has SUF-CMA (strong unforgeability under chosen message attacks). +`zip215: false` option switches verification criteria to strict +[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and additionally provides [non-repudiation with SBS](#edwards-twisted-edwards-curve). + +X25519 follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). + +```ts +// Variants from RFC8032: with context, prehashed +import { ed25519ctx, ed25519ph } from '@noble/curves/ed25519'; + +// ECDH using curve25519 aka x25519 +import { x25519 } from '@noble/curves/ed25519'; +const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4'; +const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c'; +x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases +x25519.getPublicKey(priv) === x25519.scalarMultBase(priv); +x25519.getPublicKey(x25519.utils.randomPrivateKey()); + +// ed25519 => x25519 conversion +import { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519'; +edwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey())); +edwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey()); +``` + +ristretto255 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +// hash-to-curve, ristretto255 +import { utf8ToBytes } from '@noble/hashes/utils'; +import { sha512 } from '@noble/hashes/sha512'; +import { + hashToCurve, + encodeToCurve, + RistrettoPoint, + hashToRistretto255, +} from '@noble/curves/ed25519'; + +const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee'); +hashToCurve(msg); + +const rp = RistrettoPoint.fromHex( + '6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919' +); +RistrettoPoint.BASE.multiply(2n).add(rp).subtract(RistrettoPoint.BASE).toRawBytes(); +RistrettoPoint.ZERO.equals(dp) === false; +// pre-hashed hash-to-curve +RistrettoPoint.hashToCurve(sha512(msg)); +// full hash-to-curve including domain separation tag +hashToRistretto255(msg, { DST: 'ristretto255_XMD:SHA-512_R255MAP_RO_' }); +``` + +#### ed448, X448, decaf448 + +```ts +import { ed448 } from '@noble/curves/ed448'; +const priv = ed448.utils.randomPrivateKey(); +const pub = ed448.getPublicKey(priv); +const msg = new TextEncoder().encode('whatsup'); +const sig = ed448.sign(msg, priv); +ed448.verify(sig, msg, pub); + +// Variants from RFC8032: prehashed +import { ed448ph } from '@noble/curves/ed448'; +``` + +ECDH using Curve448 aka X448, follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). + +```ts +import { x448 } from '@noble/curves/ed448'; +x448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases +x448.getPublicKey(priv) === x448.scalarMultBase(priv); + +// ed448 => x448 conversion +import { edwardsToMontgomeryPub } from '@noble/curves/ed448'; +edwardsToMontgomeryPub(ed448.getPublicKey(ed448.utils.randomPrivateKey())); +``` + +decaf448 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +import { utf8ToBytes } from '@noble/hashes/utils'; +import { shake256 } from '@noble/hashes/sha3'; +import { hashToCurve, encodeToCurve, DecafPoint, hashToDecaf448 } from '@noble/curves/ed448'; + +const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee'); +hashToCurve(msg); + +const dp = DecafPoint.fromHex( + 'c898eb4f87f97c564c6fd61fc7e49689314a1f818ec85eeb3bd5514ac816d38778f69ef347a89fca817e66defdedce178c7cc709b2116e75' +); +DecafPoint.BASE.multiply(2n).add(dp).subtract(DecafPoint.BASE).toRawBytes(); +DecafPoint.ZERO.equals(dp) === false; +// pre-hashed hash-to-curve +DecafPoint.hashToCurve(shake256(msg, { dkLen: 112 })); +// full hash-to-curve including domain separation tag +hashToDecaf448(msg, { DST: 'decaf448_XOF:SHAKE256_D448MAP_RO_' }); +``` + +Same RFC7748 / RFC8032 / IRTF draft are followed. + +#### bls12-381 + +```ts +import { bls12_381 as bls } from '@noble/curves/bls12-381'; + +// G1 keys, G2 signatures +const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c'; +const message = '64726e3da8'; +const publicKey = bls.getPublicKey(privateKey); +const signature = bls.sign(message, privateKey); +const isValid = bls.verify(signature, message, publicKey); +console.log({ publicKey, signature, isValid }); + +// G2 signatures, G1 keys +// getPublicKeyForShortSignatures(privateKey) +// signShortSignature(message, privateKey) +// verifyShortSignature(signature, message, publicKey) +// aggregateShortSignatures(signatures) + +// Custom DST +const htfEthereum = { DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' }; +const signatureEth = bls.sign(message, privateKey, htfEthereum); +const isValidEth = bls.verify(signature, message, publicKey, htfEthereum); + +// Aggregation +const aggregatedKey = bls.aggregatePublicKeys([bls.utils.randomPrivateKey(), bls.utils.randomPrivateKey()]) +// const aggregatedSig = bls.aggregateSignatures(sigs) + +// Pairings, with and without final exponentiation +// bls.pairing(PointG1, PointG2); +// bls.pairing(PointG1, PointG2, false); +// bls.fields.Fp12.finalExponentiate(bls.fields.Fp12.mul(PointG1, PointG2)); + +// Others +// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE; +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr; +``` + +See [abstract/bls](#bls-barreto-lynn-scott-curves). +For example usage, check out [the implementation of BLS EVM precompiles](https://github.com/ethereumjs/ethereumjs-monorepo/blob/361f4edbc239e795a411ac2da7e5567298b9e7e5/packages/evm/src/precompiles/bls12_381/noble.ts). + +#### bn254 aka alt_bn128 + +```ts +import { bn254 } from '@noble/curves/bn254'; + +console.log( + bn254.G1, + bn254.G2, + bn254.pairing +) +``` + +The API mirrors [BLS](#bls12-381). The curve was previously called alt_bn128. +The implementation is compatible with [EIP-196](https://eips.ethereum.org/EIPS/eip-196) and +[EIP-197](https://eips.ethereum.org/EIPS/eip-197). + +Keep in mind that we don't implement Point methods toHex / toRawBytes. It's because +different implementations of bn254 do it differently - there is no standard. Points of divergence: + +- Endianness: LE vs BE (byte-swapped) +- Flags as first hex bits (similar to BLS) vs no-flags +- Imaginary part last in G2 vs first (c0, c1 vs c1, c0) + +For example usage, check out [the implementation of bn254 EVM precompiles](https://github.com/paulmillr/noble-curves/blob/3ed792f8ad9932765b84d1064afea8663a255457/test/bn254.test.js#L697). + +#### Multi-scalar-multiplication + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +const p = secp256k1.ProjectivePoint; +const points = [p.BASE, p.BASE.multiply(2n), p.BASE.multiply(4n), p.BASE.multiply(8n)]; +p.msm(points, [3n, 5n, 7n, 11n]).equals(p.BASE.multiply(129n)); // 129*G +``` + +Pippenger algorithm is used underneath. +Multi-scalar-multiplication (MSM) is basically `(Pa + Qb + Rc + ...)`. +It's 10-30x faster vs naive addition for large amount of points. + +#### All available imports + +```typescript +import { secp256k1, schnorr } from '@noble/curves/secp256k1'; +import { ed25519, ed25519ph, ed25519ctx, x25519, RistrettoPoint } from '@noble/curves/ed25519'; +import { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448'; +import { p256 } from '@noble/curves/p256'; +import { p384 } from '@noble/curves/p384'; +import { p521 } from '@noble/curves/p521'; +import { pallas, vesta } from '@noble/curves/pasta'; +import { bls12_381 } from '@noble/curves/bls12-381'; +import { bn254 } from '@noble/curves/bn254'; // also known as alt_bn128 +import { jubjub } from '@noble/curves/jubjub'; +import { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from '@noble/curves/abstract/utils'; +``` + +#### Accessing a curve's variables + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +// Every curve has `CURVE` object that contains its parameters, field, and others +console.log(secp256k1.CURVE.p); // field modulus +console.log(secp256k1.CURVE.n); // curve order +console.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params +console.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates +``` + +## Abstract API + +Abstract API allows to define custom curves. All arithmetics is done with JS +bigints over finite fields, which is defined from `modular` sub-module. For +scalar multiplication, we use +[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). +Precomputes are enabled for weierstrass and edwards BASE points of a curve. You +could precompute any other point (e.g. for ECDH) using `utils.precompute()` +method: check out examples. + +### weierstrass: Short Weierstrass curve + +```ts +import { weierstrass } from '@noble/curves/abstract/weierstrass'; +import { Field } from '@noble/curves/abstract/modular'; // finite field for mod arithmetics +import { sha256 } from '@noble/hashes/sha256'; // 3rd-party sha256() of type utils.CHash +import { hmac } from '@noble/hashes/hmac'; // 3rd-party hmac() that will accept sha256() +import { concatBytes, randomBytes } from '@noble/hashes/utils'; // 3rd-party utilities +const secq256k1 = weierstrass({ + // secq256k1: cycle of secp256k1 with Fp/N flipped. + // https://personaelabs.org/posts/spartan-ecdsa + // https://zcash.github.io/halo2/background/curves.html#cycles-of-curves + a: 0n, + b: 7n, + Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n), + n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n, + Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n, + Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n, + hash: sha256, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(sha256, key, concatBytes(...msgs)), + randomBytes, +}); + +// Replace weierstrass() with weierstrassPoints() if you don't need ECDSA, hash, hmac, randomBytes +``` + +Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass` +expects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +**`k` generation** is done deterministically, following +[RFC6979](https://www.rfc-editor.org/rfc/rfc6979). For this you will need +`hmac` & `hash`, which in our implementations is provided by noble-hashes. If +you're using different hashing library, make sure to wrap it in the following interface: + +```ts +type CHash = { + (message: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create(): any; +}; + +// example +function sha256(message: Uint8Array) { + return _internal_lowlvl(message); +} +sha256.outputLen = 32; // 32 bytes of output for sha2-256 +``` + +**Message hash** is expected instead of message itself: + +- `sign(msgHash, privKey)` is default behavior, assuming you pre-hash msg with sha2, or other hash +- `sign(msg, privKey, {prehash: true})` option can be used if you want to pass the message itself + +**Weierstrass points:** + +1. Exported as `ProjectivePoint` +2. Represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using + `ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates + +```ts +// `weierstrassPoints()` returns `CURVE` and `ProjectivePoint` +// `weierstrass()` returns `CurveFn` +type SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array }; +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => SignatureType; + verify: ( + signature: Hex | SignatureType, + msgHash: Hex, + publicKey: Hex, + opts?: { lowS?: boolean; prehash?: boolean } + ) => boolean; + ProjectivePoint: ProjectivePointConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(key: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +// T is usually bigint, but can be something else like complex numbers in BLS curves +interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): bigint; + get y(): bigint; + multiply(scalar: bigint): ProjPointType; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods for 3d XYZ points +interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + msm(points: ProjPointType[], scalars: bigint[]): ProjPointType; +} +``` + +**ECDSA signatures** are represented by `Signature` instances and can be +described by the interface: + +```ts +interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): SignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(): Uint8Array; + toDERHex(): string; +} +type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +``` + +More examples: + +```typescript +// All curves expose same generic interface. +const priv = secq256k1.utils.randomPrivateKey(); +secq256k1.getPublicKey(priv); // Convert private key to public. +const sig = secq256k1.sign(msg, priv); // Sign msg with private key. +const sig2 = secq256k1.sign(msg, priv, { prehash: true }); // hash(msg) +secq256k1.verify(sig, msg, priv); // Verify if sig is correct. + +const Point = secq256k1.ProjectivePoint; +const point = Point.BASE; // Elliptic curve Point class and BASE point static var. +point.add(point).equals(point.double()); // add(), equals(), double() methods +point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var +point.negate(); // Flips point over x/y coordinate. +point.multiply(31415n); // Multiplication of Point by scalar. + +point.assertValidity(); // Checks for being on-curve +point.toAffine(); // Converts to 2d affine xy coordinates + +secq256k1.CURVE.n; +secq256k1.CURVE.p; +secq256k1.CURVE.Fp.mod(); +secq256k1.CURVE.hash(); + +// precomputes +const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey)); +fast.multiply(privKey); // much faster ECDH now +``` + +### edwards: Twisted Edwards curve + +```ts +import { twistedEdwards } from '@noble/curves/abstract/edwards'; +import { Field } from '@noble/curves/abstract/modular'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; + +const Fp = Field(2n ** 255n - 19n); +const ed25519 = twistedEdwards({ + a: Fp.create(-1n), + d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p + Fp: Fp, + n: 2n ** 252n + 27742317777372353535851937790883648493n, + h: 8n, + Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, + Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n, + hash: sha512, + randomBytes, + adjustScalarBytes(bytes) { + // optional; but mandatory in ed25519 + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +} as const); +``` + +Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +For EdDSA signatures, `hash` param required. `adjustScalarBytes` which instructs how to change private scalars could be specified. + +We support [non-repudiation](https://eprint.iacr.org/2020/1244), which help in following scenarios: + +- Contract Signing: if A signed an agreement with B using key that allows repudiation, it can later claim that it signed a different contract +- E-voting: malicious voters may pick keys that allow repudiation in order to deny results +- Blockchains: transaction of amount X might also be valid for a different amount Y + +**Edwards points:** + +1. Exported as `ExtendedPoint` +2. Represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates +7. Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions + +```ts +// `twistedEdwards()` returns `CurveFn` of following type: +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array; + verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: PrivKey) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: PointType; + pointBytes: Uint8Array; + }; + }; +}; + +interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; + msm(points: ExtPointType[], scalars: bigint[]): ExtPointType; +} +``` + +### montgomery: Montgomery curve + +```typescript +import { montgomery } from '@noble/curves/abstract/montgomery'; +import { Field } from '@noble/curves/abstract/modular'; + +const x25519 = montgomery({ + a: 486662n, + Gu: 9n, + P: 2n ** 255n - 19n, + montgomeryBits: 255, + nByteLength: 32, + // Optional param + adjustScalarBytes(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +}); +``` + +The module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748. +Proper Elliptic Curve Points are not implemented yet. + +You must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`. + +### bls: Barreto-Lynn-Scott curves + +The module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction. +They allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and +use aggregated, batch-verifiable +[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716), +using Boneh-Lynn-Shacham signature scheme. + +The module doesn't expose `CURVE` property: use `G1.CURVE`, `G2.CURVE` instead. +Only BLS12-381 is currently implemented. +Defining BLS12-377 and BLS24 should be straightforward. + +The default BLS uses short public keys (with public keys in G1 and signatures in G2). +Short signatures (public keys in G2 and signatures in G1) are also supported. + +### hash-to-curve: Hashing strings to curve points + +The module allows to hash arbitrary strings to elliptic curve points. Implements [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). + +Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security: + +```ts +import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1'; +import { randomBytes } from '@noble/hashes/utils'; +hashToCurve('0102abcd'); +console.log(hashToCurve(randomBytes())); +console.log(encodeToCurve(randomBytes())); + +import { bls12_381 } from '@noble/curves/bls12-381'; +bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' }); +bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' }); +``` + +Low-level methods from the spec: + +```ts +// produces a uniformly random byte string using a cryptographic hash function H that outputs b bits. +function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash // For CHash see abstract/weierstrass docs section +): Uint8Array; +// produces a uniformly random byte string using an extendable-output function (XOF) H. +function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array; +// Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F +function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand?: 'xmd' | 'xof'; + hash: CHash; +}; +``` + +### poseidon: Poseidon hash + +Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + +There are many poseidon variants with different constants. +We don't provide them: you should construct them manually. +Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + +```ts +import { poseidon } from '@noble/curves/abstract/poseidon'; + +type PoseidonOpts = { + Fp: Field; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +const instance = poseidon(opts: PoseidonOpts); +``` + +### modular: Modular arithmetics utilities + +```ts +import * as mod from '@noble/curves/abstract/modular'; +const fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19 +fp.mul(591n, 932n); // multiplication +fp.pow(481n, 11024858120n); // exponentiation +fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17) +fp.sqrt(21n); // square root + +// Generic non-FP utils are also available +mod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10 +mod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse +mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion +``` + +Field operations are not constant-time: they are using JS bigints, see [security](#security). +The fact is mostly irrelevant, but the important method to keep in mind is `pow`, +which may leak exponent bits, when used naïvely. + +`mod.Field` is always **field over prime**. Non-prime fields aren't supported for now. +We don't test for prime-ness for speed and because algorithms are probabilistic anyway. +Initializing a non-prime field could make your app suspectible to +DoS (infilite loop) on Tonelli-Shanks square root calculation. + +Unlike `mod.invert`, `mod.invertBatch` won't throw on `0`: make sure to throw an error yourself. + +#### Creating private keys from hashes + +You can't simply make a 32-byte private key from a 32-byte hash. +Doing so will make the key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/). + +To make the bias negligible, we follow [FIPS 186-5 A.2](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-5.2). +This means, for 32-byte key, we would need 48-byte hash to get 2^-128 bias, which matches curve security level. + +`hashToPrivateScalar()` that hashes to **private key** was created for this purpose. +Use [abstract/hash-to-curve](#hash-to-curve-hashing-strings-to-curve-points) +if you need to hash to **public key**. + +```ts +import { p256 } from '@noble/curves/p256'; +import { sha256 } from '@noble/hashes/sha256'; +import { hkdf } from '@noble/hashes/hkdf'; +import * as mod from '@noble/curves/abstract/modular'; +const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2) +const derived = hkdf(sha256, someKey, undefined, 'application', 48); // 48 bytes for 32-byte priv +const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n); +``` + +### utils: Useful utilities + +```ts +import * as utils from '@noble/curves/abstract/utils'; + +utils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.hexToBytes('deadbeef'); +utils.numberToHexUnpadded(123n); +utils.hexToNumber(); + +utils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.numberToBytesBE(123n, 32); +utils.numberToBytesLE(123n, 64); + +utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef])); +utils.nLength(255n); +utils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde])); +``` + +## Security + +The library has been independently audited: + +- at version 1.6.0, in Sep 2024, by [cure53](https://cure53.de) + - PDFs: [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.6.0..main) + - Scope: ed25519, ed448, their add-ons, bls12-381, bn254, + hash-to-curve, low-level primitives bls, tower, edwards, montgomery etc. +- at version 1.2.0, in Sep 2023, by [Kudelski Security](https://kudelskisecurity.com) + - PDFs: [offline](./audit/2023-09-kudelski-audit-starknet.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.2.0..main) + - Scope: [scure-starknet](https://github.com/paulmillr/scure-starknet) and its related + abstract modules of noble-curves: `curve`, `modular`, `poseidon`, `weierstrass` + - The audit has been funded by [Starkware](https://starkware.co) +- at version 0.7.3, in Feb 2023, by [Trail of Bits](https://www.trailofbits.com) + - PDFs: [online](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf), + [offline](./audit/2023-01-trailofbits-audit-curves.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main) + - Scope: abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass` and + top-level modules `_shortw_utils` and `secp256k1` + - The audit has been funded by [Ryan Shea](https://www.shea.io) + +It is tested against property-based, cross-library and Wycheproof vectors, +and has fuzzing by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +_JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to +achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +### Supply chain security + +- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures. +- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs +- **Rare releasing** is followed to ensure less re-audit need for end-users +- **Dependencies** are minimized and locked-down: + - If your app has 500 dependencies, any dep could get hacked and you'll be downloading + malware with every install. We make sure to use as few dependencies as possible + - We prevent automatic dependency updates by locking-down version ranges. Every update is checked with `npm-diff` + - One dependency [noble-hashes](https://github.com/paulmillr/noble-hashes) is used, by the same author, to provide hashing functionality +- **Dev Dependencies** are only used if you want to contribute to the repo. They are disabled for end-users: + - scure-base, scure-bip32, scure-bip39, micro-bmark and micro-should are developed by the same author and follow identical security practices + - prettier (linter), fast-check (property-based testing) and typescript are used for code quality, vector generation and ts compilation. The packages are big, which makes it hard to audit their source code thoroughly and fully + +### Randomness + +We're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +In the past, browsers had bugs that made it weak: it may happen again. +Implementing a userspace CSPRNG to get resilient to the weakness +is even worse: there is no reliable userspace source of quality entropy. + +## Speed + +Benchmark results on Apple M2 with node v22: + +``` +secp256k1 +init x 68 ops/sec @ 14ms/op +getPublicKey x 6,839 ops/sec @ 146μs/op +sign x 5,226 ops/sec @ 191μs/op +verify x 893 ops/sec @ 1ms/op +getSharedSecret x 538 ops/sec @ 1ms/op +recoverPublicKey x 923 ops/sec @ 1ms/op +schnorr.sign x 700 ops/sec @ 1ms/op +schnorr.verify x 919 ops/sec @ 1ms/op + +ed25519 +init x 51 ops/sec @ 19ms/op +getPublicKey x 9,809 ops/sec @ 101μs/op +sign x 4,976 ops/sec @ 200μs/op +verify x 1,018 ops/sec @ 981μs/op + +ed448 +init x 19 ops/sec @ 50ms/op +getPublicKey x 3,723 ops/sec @ 268μs/op +sign x 1,759 ops/sec @ 568μs/op +verify x 344 ops/sec @ 2ms/op + +p256 +init x 39 ops/sec @ 25ms/op +getPublicKey x 6,518 ops/sec @ 153μs/op +sign x 5,148 ops/sec @ 194μs/op +verify x 609 ops/sec @ 1ms/op + +p384 +init x 17 ops/sec @ 57ms/op +getPublicKey x 2,933 ops/sec @ 340μs/op +sign x 2,327 ops/sec @ 429μs/op +verify x 244 ops/sec @ 4ms/op + +p521 +init x 8 ops/sec @ 112ms/op +getPublicKey x 1,484 ops/sec @ 673μs/op +sign x 1,264 ops/sec @ 790μs/op +verify x 124 ops/sec @ 8ms/op + +ristretto255 +add x 680,735 ops/sec @ 1μs/op +multiply x 10,766 ops/sec @ 92μs/op +encode x 15,835 ops/sec @ 63μs/op +decode x 15,972 ops/sec @ 62μs/op + +decaf448 +add x 345,303 ops/sec @ 2μs/op +multiply x 300 ops/sec @ 3ms/op +encode x 5,987 ops/sec @ 167μs/op +decode x 5,892 ops/sec @ 169μs/op + +ecdh +├─x25519 x 1,477 ops/sec @ 676μs/op +├─secp256k1 x 537 ops/sec @ 1ms/op +├─p256 x 512 ops/sec @ 1ms/op +├─p384 x 198 ops/sec @ 5ms/op +├─p521 x 99 ops/sec @ 10ms/op +└─x448 x 504 ops/sec @ 1ms/op + +bls12-381 +init x 36 ops/sec @ 27ms/op +getPublicKey x 960 ops/sec @ 1ms/op +sign x 60 ops/sec @ 16ms/op +verify x 47 ops/sec @ 21ms/op +pairing x 125 ops/sec @ 7ms/op +pairing10 x 40 ops/sec @ 24ms/op ± 23.27% (min: 21ms, max: 48ms) +MSM 4096 scalars x points x 0 ops/sec @ 4655ms/op +aggregatePublicKeys/8 x 129 ops/sec @ 7ms/op +aggregatePublicKeys/32 x 34 ops/sec @ 28ms/op +aggregatePublicKeys/128 x 8 ops/sec @ 113ms/op +aggregatePublicKeys/512 x 2 ops/sec @ 449ms/op +aggregatePublicKeys/2048 x 0 ops/sec @ 1792ms/op +aggregateSignatures/8 x 62 ops/sec @ 15ms/op +aggregateSignatures/32 x 16 ops/sec @ 60ms/op +aggregateSignatures/128 x 4 ops/sec @ 238ms/op +aggregateSignatures/512 x 1 ops/sec @ 946ms/op +aggregateSignatures/2048 x 0 ops/sec @ 3774ms/op + +hash-to-curve +hash_to_field x 91,600 ops/sec @ 10μs/op +secp256k1 x 2,373 ops/sec @ 421μs/op +p256 x 4,310 ops/sec @ 231μs/op +p384 x 1,664 ops/sec @ 600μs/op +p521 x 807 ops/sec @ 1ms/op +ed25519 x 3,088 ops/sec @ 323μs/op +ed448 x 1,247 ops/sec @ 801μs/op +``` + +## Upgrading + +Previously, the library was split into single-feature packages +[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1), +[noble-ed25519](https://github.com/paulmillr/noble-ed25519) and +[noble-bls12-381](https://github.com/paulmillr/noble-bls12-381). + +Curves continue their original work. The single-feature packages changed their +direction towards providing minimal 4kb implementations of cryptography, +which means they have less features. + +Upgrading from noble-secp256k1 2.0 or noble-ed25519 2.0: no changes, libraries are compatible. + +Upgrading from noble-secp256k1 1.7: + +- `getPublicKey` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getPublicKey(priv, false)` +- `sign` + - is now sync + - now returns `Signature` instance with `{ r, s, recovery }` properties + - `canonical` option was renamed to `lowS` + - `recovered` option has been removed because recovery bit is always returned now + - `der` option has been removed. There are 2 options: + 1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`. + Compact encoding is simply a concatenation of 32-byte r and 32-byte s. + 2. If you must use DER encoding, switch to noble-curves (see above). +- `verify` + - is now sync + - `strict` option was renamed to `lowS` +- `getSharedSecret` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getSharedSecret(a, b, false)` +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `number` type for private keys have been removed: use `bigint` instead +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`hmacSha256Sync` and others) + +Upgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7: + +- Methods are now sync by default +- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs +- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt) +- `Signature` was removed: just use raw bytes or hex now +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`sha512Sync` and others) +- `getSharedSecret` was moved to `x25519` module +- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods + +Upgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381): + +- Methods and classes were renamed: + - PointG1 -> G1.Point, PointG2 -> G2.Point + - PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode +- Fp2 ORDER was corrected + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests + +## Resources + +Check out [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts b/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts new file mode 100644 index 0000000..39244c6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts @@ -0,0 +1,62 @@ +import { randomBytes } from '@noble/hashes/utils'; +import { CHash } from './abstract/utils.js'; +import { CurveType } from './abstract/weierstrass.js'; +export declare function getHash(hash: CHash): { + hash: CHash; + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array; + randomBytes: typeof randomBytes; +}; +type CurveDef = Readonly>; +export declare function createCurve(curveDef: CurveDef, defHash: CHash): Readonly<{ + create: (hash: CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export {}; +//# sourceMappingURL=_shortw_utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts.map b/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts.map new file mode 100644 index 0000000..8452638 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/_shortw_utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AAGnE,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK;;gBAGnB,UAAU,WAAW,UAAU,EAAE;;EAGhD;AAED,KAAK,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAC3E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK;mBACtC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAG01zB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;GADzi2B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/_shortw_utils.js b/src/libMPC/node_modules/@noble/curves/_shortw_utils.js new file mode 100644 index 0000000..ea1ea56 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/_shortw_utils.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getHash = getHash; +exports.createCurve = createCurve; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const hmac_1 = require("@noble/hashes/hmac"); +const utils_1 = require("@noble/hashes/utils"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)), + randomBytes: utils_1.randomBytes, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/_shortw_utils.js.map b/src/libMPC/node_modules/@noble/curves/_shortw_utils.js.map new file mode 100644 index 0000000..9a14682 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":";;AAOA,0BAMC;AAGD,kCAGC;AAnBD,sEAAsE;AACtE,6CAA0C;AAC1C,+CAA+D;AAE/D,8DAAmE;AAEnE,wCAAwC;AACxC,SAAgB,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAA,WAAI,EAAC,IAAI,EAAE,GAAG,EAAE,IAAA,mBAAW,EAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW,EAAX,mBAAW;KACZ,CAAC;AACJ,CAAC;AAGD,SAAgB,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,IAAA,4BAAW,EAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts new file mode 100644 index 0000000..02e1ff2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts @@ -0,0 +1,125 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +import { Hex, PrivKey, CHash } from './utils.js'; +import { MapToCurve, Opts as HTFOpts, htfBasicOpts, createHasher } from './hash-to-curve.js'; +import { CurvePointsType, ProjPointType as ProjPointType, CurvePointsRes } from './weierstrass.js'; +import type { Fp2, Fp6, Fp12, Fp2Bls, Fp12Bls } from './tower.js'; +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two main ways to use it: + * 1. Fp for short private keys, Fp₂ for signatures + * 2. Fp for short signatures, Fp₂ for private keys + **/ +type Fp = bigint; +export type TwistType = 'multiplicative' | 'divisive'; +export type ShortSignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type CurveType = { + G1: Omit, 'n'> & { + ShortSignature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + }; + params: { + ateLoopSize: bigint; + xNegative: boolean; + r: bigint; + twistType: TwistType; + }; + htfDefaults: HTFOpts; + hash: CHash; + randomBytes: (bytesLength?: number) => Uint8Array; + postPrecompute?: (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2, pointAdd: (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => { + Rx: Fp2; + Ry: Fp2; + Rz: Fp2; + }) => void; +}; +type PrecomputeSingle = [Fp2, Fp2, Fp2][]; +type Precompute = PrecomputeSingle[]; +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + getPublicKeyForShortSignatures: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + signShortSignature: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + verify: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType, htfOpts?: htfBasicOpts) => boolean; + verifyShortSignature: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType, htfOpts?: htfBasicOpts) => boolean; + verifyBatch: (signature: Hex | ProjPointType, messages: (Hex | ProjPointType)[], publicKeys: (Hex | ProjPointType)[], htfOpts?: htfBasicOpts) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + aggregateShortSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + pairingBatch: (pairs: { + g1: ProjPointType; + g2: ProjPointType; + }[], withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + ShortSignature: ShortSignatureCoder; + params: { + ateLoopSize: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: ProjPointType) => Precompute; + }; +}; +export declare function bls(CURVE: CurveType): CurveFn; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts.map new file mode 100644 index 0000000..27cfc5c --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAGtE,OAAO,EAAE,MAAM,EAAoC,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAyB,MAAM,YAAY,CAAC;AAExE,OAAO,EACL,UAAU,EAAE,IAAI,IAAI,OAAO,EAAuB,YAAY,EAC9D,YAAY,EACb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,eAAe,EACf,aAAa,IAAI,aAAa,EAC9B,cAAc,EAEf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAElE;;;;;;;;;;;;;;IAcI;AAEJ,KAAK,EAAE,GAAG,MAAM,CAAC;AAKjB,MAAM,MAAM,SAAS,GAAG,gBAAgB,GAAG,UAAU,CAAC;AAEtD,MAAM,MAAM,mBAAmB,CAAC,EAAE,IAAI;IACpC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,aAAa,CAAC,EAAE,CAAC,CAAC;IACrC,UAAU,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC;IACjD,KAAK,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,cAAc,CAAC,EAAE,IAAI;IAC/B,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,aAAa,CAAC,EAAE,CAAC,CAAC;IACrC,UAAU,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC;IACjD,K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bls.js b/src/libMPC/node_modules/@noble/curves/abstract/bls.js new file mode 100644 index 0000000..e860ae7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/bls.js @@ -0,0 +1,340 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls = bls; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. +// TODO: import { AffinePoint } from './curve.js'; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +// prettier-ignore +const hash_to_curve_js_1 = require("./hash-to-curve.js"); +const weierstrass_js_1 = require("./weierstrass.js"); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// Not used with BLS12-381 (no sequential `11` in X). Useful for other curves. +function NAfDecomposition(a) { + const res = []; + // a>1 because of marker bit + for (; a > _1n; a >>= _1n) { + if ((a & _1n) === _0n) + res.unshift(0); + else if ((a & _3n) === _3n) { + res.unshift(-1); + a += _1n; + } + else + res.unshift(1); + } + return res; +} +function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_IS_NEGATIVE = CURVE.params.xNegative; + const TWIST = CURVE.params.twistType; + // Point on G1 curve: (x, y) + const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, (0, hash_to_curve_js_1.createHasher)(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, (0, hash_to_curve_js_1.createHasher)(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + // Applies sparse multiplication as line function + let lineFunction; + if (TWIST === 'multiplicative') { + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); + } + else if (TWIST === 'divisive') { + // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of + // precompute calculations. + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); + } + else + throw new Error('bls: unknown twist type'); + const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n)); + function pointDouble(ell, Rx, Ry, Rz) { + const t0 = Fp2.sqr(Ry); // Ry² + const t1 = Fp2.sqr(Rz); // Rz² + const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + const t3 = Fp2.mul(t2, _3n); // 3 * T2 + const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + const c0 = Fp2.sub(t2, t0); // T2 - T0 (i) + const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx² + const c2 = Fp2.neg(t4); // -T4 (-h) + ell.push([c0, c1, c2]); + Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + return { Rx, Ry, Rz }; + } + function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) { + // Addition + const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy + const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry + const c2 = t1; // == Rx - Qx * Rz + ell.push([c0, c1, c2]); + const t2 = Fp2.sqr(t1); // T1² + const t3 = Fp2.mul(t2, t1); // T2 * T1 + const t4 = Fp2.mul(t2, Rx); // T2 * Rx + const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + return { Rx, Ry, Rz }; + } + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine + // add + double in windowed precomputes here, otherwise it would be single op (since X is static) + const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize); + const calcPairingPrecomputes = (0, utils_js_1.memoized)((point) => { + const p = point; + const { x, y } = p.toAffine(); + // prettier-ignore + const Qx = x, Qy = y, negQy = Fp2.neg(y); + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; + const ell = []; + for (const bit of ATE_NAF) { + const cur = []; + ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); + if (bit) + ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); + ell.push(cur); + } + if (CURVE.postPrecompute) { + const last = ell[ell.length - 1]; + CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); + } + return ell; + }); + function millerLoopBatch(pairs, withFinalExponent = false) { + let f12 = Fp12.ONE; + if (pairs.length) { + const ellLen = pairs[0][0].length; + for (let i = 0; i < ellLen; i++) { + f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings + // NOTE: we apply multiple pairings in parallel here + for (const [ell, Px, Py] of pairs) { + for (const [c0, c1, c2] of ell[i]) + f12 = lineFunction(c0, c1, c2, f12, Px, Py); + } + } + } + if (BLS_X_IS_NEGATIVE) + f12 = Fp12.conjugate(f12); + return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; + } + // Calculates product of multiple pairings + // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))` + function pairingBatch(pairs, withFinalExponent = true) { + const res = []; + // This cache precomputed toAffine for all points + G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1)); + G2.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2)); + for (const { g1, g2 } of pairs) { + if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + // This uses toAffine inside + g1.assertValidity(); + g2.assertValidity(); + const Qa = g1.toAffine(); + res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]); + } + return millerLoopBatch(res, withFinalExponent); + } + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + return pairingBatch([{ g1: Q, g2: P }], withFinalExponent); + } + const utils = { + randomPrivateKey: () => { + const length = (0, modular_js_1.getMinHashLength)(Fr.ORDER); + return (0, modular_js_1.mapHashToField)(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + const { ShortSignature } = CURVE.G1; + const { Signature } = CURVE.G2; + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP1Hash(point, htfOpts) { + return point instanceof G1.ProjectivePoint + ? point + : G1.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts); + } + // Multiplies generator (G1) by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + // Multiplies generator (G2) by private key. + // P = pk x G + function getPublicKeyForShortSignatures(privateKey) { + return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + function signShortSignature(message, privateKey, htfOpts) { + const msgPoint = normP1Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G1.ProjectivePoint) + return sigPoint; + return ShortSignature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + const exp = pairingBatch([ + { g1: P.negate(), g2: Hm }, // ePHM = pairing(P.negate(), Hm, false); + { g1: G, g2: S }, // eGS = pairing(G, S, false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(S, G) == e(H(m), P) + function verifyShortSignature(signature, message, publicKey, htfOpts) { + const P = normP2(publicKey); + const Hm = normP1Hash(message, htfOpts); + const G = G2.ProjectivePoint.BASE; + const S = normP1(signature); + const exp = pairingBatch([ + { g1: Hm, g2: P }, // eHmP = pairing(Hm, P, false); + { g1: S, g2: G.negate() }, // eSG = pairing(S, G.negate(), false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + function aggregateShortSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return ShortSignature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, + // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead? + messages, publicKeys, htfOpts) { + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + // NOTE: this works only for exact same object + const messagePubKeyMap = new Map(); + for (let i = 0; i < nPublicKeys.length; i++) { + const pub = nPublicKeys[i]; + const msg = nMessages[i]; + let keys = messagePubKeyMap.get(msg); + if (keys === undefined) { + keys = []; + messagePubKeyMap.set(msg, keys); + } + keys.push(pub); + } + const paired = []; + try { + for (const [msg, keys] of messagePubKeyMap) { + const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg)); + paired.push({ g1: groupPublicKey, g2: msg }); + } + paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig }); + return Fp12.eql(pairingBatch(paired), Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + getPublicKeyForShortSignatures, + sign, + signShortSignature, + verify, + verifyBatch, + verifyShortSignature, + aggregatePublicKeys, + aggregateSignatures, + aggregateShortSignatures, + millerLoopBatch, + pairing, + pairingBatch, + G1, + G2, + Signature, + ShortSignature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + ateLoopSize: CURVE.params.ateLoopSize, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/bls.js.map b/src/libMPC/node_modules/@noble/curves/abstract/bls.js.map new file mode 100644 index 0000000..c9dab94 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":";;AAqLA,kBAsXC;AA3iBD,sEAAsE;AACtE,8DAA8D;AAC9D,kDAAkD;AAClD,6CAAwE;AACxE,yCAAwE;AACxE,kBAAkB;AAClB,yDAG4B;AAC5B,qDAK0B;AAqB1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAkIzE,8EAA8E;AAC9E,SAAS,gBAAgB,CAAC,CAAS;IACjC,MAAM,GAAG,GAAG,EAAE,CAAC;IACf,4BAA4B;IAC5B,OAAO,CAAC,GAAG,GAAG,EAAE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PC/node_modules/@noble/curves/abstract/curve.d.ts new file mode 100644 index 0000000..79fd78a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts @@ -0,0 +1,83 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type AffinePoint = { + x: T; + y: T; +} & { + z?: never; + t?: never; +}; +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; +export declare function wNAF>(c: GroupConstructor, bits: number): { + constTimeNegate: (condition: boolean, item: T) => T; + unsafeLadder(elm: T, n: bigint): T; + /** + * 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. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[]; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { + p: T; + f: T; + }; + wNAFCached(P: T, n: bigint, transform: Mapper): { + p: T; + f: T; + }; + setWindowSize(P: T, W: number): void; +}; +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with 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 field 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 private keys / bigints) + */ +export declare function pippenger>(c: GroupConstructor, field: IField, points: T[], scalars: bigint[]): T; +export type BasicCurve = { + Fp: IField; + n: bigint; + nBitLength?: number; + nByteLength?: number; + h: bigint; + hEff?: bigint; + Gx: T; + Gy: T; + allowInfinityPoint?: boolean; +}; +export declare function validateBasic(curve: BasicCurve & T): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; +} & BasicCurve & T & { + p: bigint; +}>; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts.map new file mode 100644 index 0000000..c41004a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAA0B,MAAM,cAAc,CAAC;AAK9D,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,GAAG;IAAE,CAAC,CAAC,EAAE,KAAK,CAAC;IAAC,CAAC,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE7B,MAAM,WAAW,KAAK,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC;IACvC,MAAM,IAAI,CAAC,CAAC;IACZ,MAAM,IAAI,CAAC,CAAC;IACZ,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACjB,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACtB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;CAC7B;AAED,MAAM,MAAM,gBAAgB,C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V,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,CAAC,CAAC;IACN,EAAE,EAAE,CAAC,CAAC;IACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC;;;;;GAqB7D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/curve.js b/src/libMPC/node_modules/@noble/curves/abstract/curve.js new file mode 100644 index 0000000..5b03e96 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/curve.js @@ -0,0 +1,230 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wNAF = wNAF; +exports.pippenger = pippenger; +exports.validateBasic = validateBasic; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// 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 +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.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. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + 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. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // 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. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // 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 }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // 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. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with 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 field 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 private keys / bigints) + */ +function pippenger(c, field, 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 + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = (0, utils_js_1.bitLen)(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.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 = c.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; +} +function validateBasic(curve) { + (0, modular_js_1.validateField)(curve.Fp); + (0, utils_js_1.validateObject)(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/curve.js.map b/src/libMPC/node_modules/@noble/curves/abstract/curve.js.map new file mode 100644 index 0000000..a4cffcf --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":";;AA2CA,oBA0IC;AAaD,8BA2CC;AAgBD,sCAqBC;AAlRD,sEAAsE;AACtE,0BAA0B;AAC1B,6CAA8D;AAC9D,yCAAoD;AACpD,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,mFAAmF;AACnF,gDAAgD;AAChD,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAc,CAAC;AACnD,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAe,CAAC,CAAC,iEAAiE;AAEtH,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D;AAC5D,+EAA+E;AAC/E,oGAAoG;AACpG,oGAAoG;AACpG,qCAAqC;AACrC,kGAAkG;AAClG,gGAAgG;AAChG,8CAA8C;AAC9C,SAAgB,IAAI,CAAqB,CAAsB,EAAE,IAAY;IAC3E,MAAM,eAAe,GAAG,CAAC,SAAkB,EAAE,IAAO,EAAK,EAAE;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC,CAAC;IACF,MAAM,SAAS,GAAG,CAAC,CAAS,EAAE,EAAE;QAC9B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI;YAChD,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,mBAAmB,IAAI,GAAG,CAAC,CAAC;IACtE,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,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AC,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3D,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5B,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxB,CAAC;QACD,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,KAAK,CAAC;YAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE;gBAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC;IACvE,CAAC;IACD,OAAO,GAAQ,CAAC;AAClB,CAAC;AAgBD,SAAgB,aAAa,CAAQ,KAAyB;IAC5D,IAAA,0BAAa,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACxB,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,IAAA,oBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts new file mode 100644 index 0000000..469275d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts @@ -0,0 +1,101 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { AffinePoint, BasicCurve, Group, GroupConstructor } from './curve.js'; +import { FHash, Hex } from './utils.js'; +export type CurveType = BasicCurve & { + a: bigint; + d: bigint; + hash: FHash; + randomBytes: (bytesLength?: number) => Uint8Array; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + prehash?: FHash; + mapToCurve?: (scalar: bigint[]) => AffinePoint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly d: bigint; + readonly hash: FHash; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + readonly adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + readonly domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + readonly uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + readonly prehash?: FHash; + readonly mapToCurve?: (scalar: bigint[]) => AffinePoint; + readonly p: bigint; +}>; +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; + msm(points: ExtPointType[], scalars: bigint[]): ExtPointType; +} +/** + * Edwards Curve interface. + * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`. + */ +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { + context?: Hex; + }) => Uint8Array; + verify: (sig: Hex, message: Hex, publicKey: Hex, options?: { + context?: Hex; + zip215: boolean; + }) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +export declare function twistedEdwards(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts.map new file mode 100644 index 0000000..5306daa --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/edwards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EACL,WAAW,EACX,UAAU,EACV,KAAK,EACL,gBAAgB,EAIjB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAe,KAAK,EAAE,GAAG,EAAmB,MAAM,YAAY,CAAC;AAOtE,MAAM,MAAM,SAAS,GAAG,UAAU,CA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C,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,GAAG,CAAA;KAAE,KAAK,UAAU,CAAC;IACjF,MAAM,EAAE,CACN,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,GAAG,EACZ,SAAS,EAAE,GAAG,EACd,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,KACzC,OAAO,CAAC;IACb,aAAa,EAAE,mBAAmB,CAAC;IACnC,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,oBAAoB,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;YAClC,IAAI,EAAE,UAAU,CAAC;YACjB,MAAM,EAAE,UAAU,CAAC;YACnB,MAAM,EAAE,MAAM,CAAC;YACf,KAAK,EAAE,YAAY,CAAC;YACpB,UAAU,EAAE,UAAU,CAAC;SACxB,CAAC;KACH,CAAC;CACH,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAua3D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/edwards.js b/src/libMPC/node_modules/@noble/curves/abstract/edwards.js new file mode 100644 index 0000000..ef735ff --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/edwards.js @@ -0,0 +1,437 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.twistedEdwards = twistedEdwards; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +const curve_js_1 = require("./curve.js"); +const modular_js_1 = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + const Fn = (0, modular_js_1.Field)(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + (0, utils_js_1.abool)('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + ut.aInRange('coordinate ' + title, n, _0n, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = (0, utils_js_1.memoized)((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = (0, utils_js_1.memoized)((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return (0, curve_js_1.pippenger)(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[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 private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array + (0, utils_js_1.abool)('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + ut.aInRange('pointHex.y', y, _0n, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = (0, curve_js_1.wNAF)(Point, nByteLength * 8); + function modN(a) { + return (0, modular_js_1.mod)(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = (0, utils_js_1.ensureBytes)('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return (0, utils_js_1.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked. + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (zip215 !== undefined) + (0, utils_js_1.abool)('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/edwards.js.map b/src/libMPC/node_modules/@noble/curves/abstract/edwards.js.map new file mode 100644 index 0000000..ff125f5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":";;AAqHA,wCAuaC;AA5hBD,sEAAsE;AACtE,8DAA8D;AAC9D,yCAQoB;AACpB,6CAA0C;AAC1C,iCAAiC;AACjC,yCAAsE;AAEtE,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG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/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..03f910b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts @@ -0,0 +1,58 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { AffinePoint, Group, GroupConstructor } from './curve.js'; +import { IField } from './modular.js'; +import type { CHash } from './utils.js'; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; +export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array; +export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * 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 declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +export declare function isogenyMap>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => { + x: T; + y: T; +}; +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +export type htfBasicOpts = { + DST: UnicodeOrBytes; +}; +export declare function createHasher(Point: H2CPointConstructor, mapToCurve: MapToCurve, def: Opts & { + encodeDST?: UnicodeOrBytes; +}): { + hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + mapToCurve(scalars: bigint[]): H2CPoint; +}; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..0c5e1a6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,MAAM,EAAO,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGxC;;;;;;;GAOG;AACH,KAAK,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AAC1C,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,cAAc,CAAC;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,IAAI,EAAE,KAAK,CAAC;CACb,CAAC;AAkCF,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,UAAU,EACf,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,KA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GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAAC;AAEnD,wBAAgB,YAAY,CAAC,CAAC,EAC5B,KAAK,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC7B,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,EACzB,GAAG,EAAE,IAAI,GAAG;IAAE,SAAS,CAAC,EAAE,cAAc,CAAA;CAAE;qBAMvB,UAAU,YAAY,YAAY;uBAWhC,UAAU,YAAY,YAAY;wBAOjC,MAAM,EAAE;EAU/B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js new file mode 100644 index 0000000..56576c9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js @@ -0,0 +1,182 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.expand_message_xmd = expand_message_xmd; +exports.expand_message_xof = expand_message_xof; +exports.hash_to_field = hash_to_field; +exports.isogenyMap = isogenyMap; +exports.createHasher = createHasher; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = utils_js_1.bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + anum(value); + anum(length); + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + 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'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +function expand_message_xmd(msg, DST, lenInBytes, H) { + (0, utils_js_1.abytes)(msg); + (0, utils_js_1.abytes)(DST); + anum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) + DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.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 = (0, utils_js_1.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((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H((0, utils_js_1.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((0, utils_js_1.concatBytes)(...args)); + } + const pseudo_random_bytes = (0, utils_js_1.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. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +function expand_message_xof(msg, DST, lenInBytes, k, H) { + (0, utils_js_1.abytes)(msg); + (0, utils_js_1.abytes)(DST); + anum(lenInBytes); + // 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((0, utils_js_1.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 + * 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. + */ +function hash_to_field(msg, count, options) { + (0, utils_js_1.validateObject)(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + (0, utils_js_1.abytes)(msg); + anum(count); + const DST = typeof _DST === 'string' ? (0, utils_js_1.utf8ToBytes)(_DST) : _DST; + 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] = (0, modular_js_1.mod)(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error('mapToCurve: expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') + throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); + const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js.map b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..5fe4284 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":";;AAwDA,gDA0BC;AAOD,gDA2BC;AAUD,sCAqCC;AAED,gCAWC;AAmBD,oCAqCC;AAtOD,6CAA2C;AAE3C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nB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts new file mode 100644 index 0000000..c7ccfad --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts @@ -0,0 +1,127 @@ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * 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 declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +export declare function invert(number: bigint, modulo: bigint): bigint; +/** + * 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 + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export declare function tonelliShanks(P: bigint): (Fp: IField, n: T) => T; +export declare function FpSqrt(P: bigint): (Fp: IField, n: T) => T; +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + isOdd?(num: T): boolean; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + cmov(a: T, b: T, c: boolean): T; +} +export declare function validateField(field: IField): IField; +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +export declare function FpPow(f: IField, num: T, power: bigint): T; +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export declare function FpInvertBatch(f: IField, nums: T[]): T[]; +export declare function FpDiv(f: IField, lhs: T, rhs: T | bigint): T; +export declare function FpLegendre(order: bigint): (f: IField, x: T) => T; +export declare function FpIsSquare(f: IField): (x: T) => boolean; +export declare function nLength(n: bigint, nBitLength?: number): { + nBitLength: number; + nByteLength: number; +}; +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * 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 doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial>): Readonly; +export declare function FpSqrtOdd(Fp: IField, elm: T): T; +export declare function FpSqrtEven(Fp: IField, elm: T): T; +/** + * "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 declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint; +/** + * 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 declare function getFieldBytesLength(fieldOrder: bigint): number; +/** + * 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 declare function getMinHashLength(fieldOrder: bigint): number; +/** + * "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 declare function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE?: boolean): Uint8Array; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts.map new file mode 100644 index 0000000..2789093 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAmBA,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAGhD;AACD;;;;;GAKG;AAEH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAUtE;AAGD,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAOrE;AAGD,wBAAgB,MAAM,C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AClB,IAAI,UAAQ,GACX,MAAM,CAQR;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAI9D;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,UAAQ,GAAG,UAAU,CAW5F"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/modular.js b/src/libMPC/node_modules/@noble/curves/abstract/modular.js new file mode 100644 index 0000000..bcce3ac --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/modular.js @@ -0,0 +1,450 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNegativeLE = void 0; +exports.mod = mod; +exports.pow = pow; +exports.pow2 = pow2; +exports.invert = invert; +exports.tonelliShanks = tonelliShanks; +exports.FpSqrt = FpSqrt; +exports.validateField = validateField; +exports.FpPow = FpPow; +exports.FpInvertBatch = FpInvertBatch; +exports.FpDiv = FpDiv; +exports.FpLegendre = FpLegendre; +exports.FpIsSquare = FpIsSquare; +exports.nLength = nLength; +exports.Field = Field; +exports.FpSqrtOdd = FpSqrtOdd; +exports.FpSqrtEven = FpSqrtEven; +exports.hashToPrivateScalar = hashToPrivateScalar; +exports.getFieldBytesLength = getFieldBytesLength; +exports.getMinHashLength = getMinHashLength; +exports.mapHashToField = mapHashToField; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +const utils_js_1 = require("./utils.js"); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +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 + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // 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); +} +/** + * 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 + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: 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) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +function FpSqrt(P) { + // NOTE: 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). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + 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)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(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 + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 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.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +exports.isNegativeLE = isNegativeLE; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return (0, utils_js_1.validateObject)(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +function FpLegendre(order) { + // (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) + const legendreConst = (order - _1n) / _2n; // Integer arithmetic + return (f, x) => f.pow(x, legendreConst); +} +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendre = FpLegendre(f.ORDER); + return (x) => { + const p = legendre(f, x); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * 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 doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: (0, utils_js_1.bitMask)(BITS), + ZERO: _0n, + ONE: _1n, + 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, + 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: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); + }, + }); + return Object.freeze(f); +} +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); +} +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 + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = (0, utils_js_1.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 ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.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 + */ +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 + */ +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 + */ +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 ? (0, utils_js_1.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(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 ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen); +} +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/modular.js.map b/src/libMPC/node_modules/@noble/curves/abstract/modular.js.map new file mode 100644 index 0000000..751b019 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":";;;AAmBA,kBAGC;AAQD,kBAUC;AAGD,oBAOC;AAGD,wBAsBC;AAUD,sCAsDC;AAED,wBA0DC;AAqDD,sCAYC;AAQD,sBAcC;AAMD,sCAiBC;AAED,sBAEC;AAED,gCAMC;AAGD,gCAMC;AAGD,0BAKC;AAkBD,sBAuDC;AAED,8BAIC;AAED,gCAIC;AAQD,kDAYC;AAQD,kDAIC;AASD,4CAGC;AAeD,wCAWC;AA7eD,sEAAsE;AACtE,sDAAsD;AACtD,yCAQoB;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM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CAAC,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,UAAkB;IACjD,MAAM,MAAM,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAC/C,OAAO,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,cAAc,CAAC,GAAe,EAAE,UAAkB,EAAE,IAAI,GAAG,KAAK;IAC9E,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC;IACvB,MAAM,QAAQ,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;IAC5C,iGAAiG;IACjG,IAAI,GAAG,GAAG,EAAE,IAAI,GAAG,GAAG,MAAM,IAAI,GAAG,GAAG,IAAI;QACxC,MAAM,IAAI,KAAK,CAAC,YAAY,MAAM,6BAA6B,GAAG,EAAE,CAAC,CAAC;IACxE,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,GAAG,CAAC,CAAC;IAC/D,+EAA+E;IAC/E,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;IACjD,OAAO,IAAI,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACxF,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts new file mode 100644 index 0000000..69e2bc4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts @@ -0,0 +1,26 @@ +type Hex = string | Uint8Array; +export type CurveType = { + P: bigint; + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { + randomPrivateKey: () => Uint8Array; + }; + GuBytes: Uint8Array; +}; +export declare function montgomery(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..fcb493a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAYA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,CAAC,EAAE,MAAM,CAAC;IACV,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD,CAAC;AACF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAuBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAmIvD"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js new file mode 100644 index 0000000..67efd56 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js @@ -0,0 +1,153 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.montgomery = montgomery; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + (0, utils_js_1.validateObject)(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => (0, modular_js_1.mod)(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => (0, modular_js_1.pow)(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + (0, utils_js_1.aInRange)('u', u, _0n, P); + (0, utils_js_1.aInRange)('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return (0, utils_js_1.numberToBytesLE)(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = (0, utils_js_1.ensureBytes)('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return (0, utils_js_1.bytesToNumberLE)(u); + } + function decodeScalar(n) { + const bytes = (0, utils_js_1.ensureBytes)('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return (0, utils_js_1.bytesToNumberLE)(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js.map b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js.map new file mode 100644 index 0000000..64fa327 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":";;AAwDA,gCAmIC;AA3LD,sEAAsE;AACtE,6CAAwC;AACxC,yCAMoB;AAEpB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;KACZ,EACD;QACE,cAAc,EAAE,eAAe;QAC/B,WAAW,EAAE,eAAe;QAC5B,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,UAAU;QACtB,EAAE,EAAE,QAAQ;KACb,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,EAAW,CAAC,CAAC;AAC9C,CAAC;AAED,4IAA4I;AAC5I,0CAA0C;AAC1C,SAAgB,UAAU,CAAC,QAAmB;IAC5C,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IACrC,MAAM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KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts new file mode 100644 index 0000000..b2197b3 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +export declare function validateOpts(opts: PoseidonOpts): Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; +}>; +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +export declare function poseidon(opts: PoseidonOpts): { + (values: bigint[]): bigint[]; + roundConstants: bigint[][]; +}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..28d7e49 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAS,MAAM,EAAiB,MAAM,cAAc,CAAC;AAG5D,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY;;gBA0C5B,MAAM;;;QApDnB,MAAM,CAAC,MAAM,CAAC;OACf,MAAM;gBACG,MAAM;mBACH,MAAM;gBACT,MAAM;2BACK,OAAO;GAqD/B;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,cAarD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY;aAcU,MAAM,EAAE;;EAsB5D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js new file mode 100644 index 0000000..7f16bc2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js @@ -0,0 +1,113 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateOpts = validateOpts; +exports.splitConstants = splitConstants; +exports.poseidon = poseidon; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +const modular_js_1 = require("./modular.js"); +function validateOpts(opts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + (0, modular_js_1.validateField)(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) + throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + if (roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => (0, modular_js_1.FpPow)(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} +function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +function poseidon(opts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js.map b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js.map new file mode 100644 index 0000000..df184d6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":";;AAgBA,oCAgDC;AAED,wCAaC;AAED,4BAoCC;AArHD,sEAAsE;AACtE,sFAAsF;AACtF,6CAA4D;AAc5D,SAAgB,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACxE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAEzD,IAAA,0BAAa,EAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE,CAAC;QAC9D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnF,CAAC;IAED,oBAAoB;IACpB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC3F,MAAM,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC9B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC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B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,cAAc,CAAC;IAC7C,OAAO,YAAY,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts new file mode 100644 index 0000000..9a8afcf --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts @@ -0,0 +1,107 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import type { ProjConstructor, ProjPointType } from './weierstrass.js'; +export type BigintTuple = [bigint, bigint]; +export type Fp = bigint; +export type Fp2 = { + c0: bigint; + c1: bigint; +}; +export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +export type Fp6 = { + c0: Fp2; + c1: Fp2; + c2: Fp2; +}; +export type Fp12 = { + c0: Fp6; + c1: Fp6; +}; +export type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +export type Fp2Bls = mod.IField & { + reim: (num: Fp2) => { + re: Fp; + im: Fp; + }; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + fromBigTuple(num: [bigint, bigint]): Fp2; +}; +export type Fp12Bls = mod.IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; +}; +export declare function psiFrobenius(Fp: mod.IField, Fp2: Fp2Bls, base: Fp2): { + psi: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + G2psi: (c: ProjConstructor, P: ProjPointType) => ProjPointType; + G2psi2: (c: ProjConstructor, P: ProjPointType) => ProjPointType; + PSI_X: Fp2; + PSI_Y: Fp2; + PSI2_X: Fp2; + PSI2_Y: Fp2; +}; +export type Tower12Opts = { + ORDER: bigint; + NONRESIDUE?: Fp; + FP2_NONRESIDUE: BigintTuple; + Fp2sqrt?: (num: Fp2) => Fp2; + Fp2mulByB: (num: Fp2) => Fp2; + Fp12cyclotomicSquare: (num: Fp12) => Fp12; + Fp12cyclotomicExp: (num: Fp12, n: bigint) => Fp12; + Fp12finalExponentiate: (num: Fp12) => Fp12; +}; +export declare function tower12(opts: Tower12Opts): { + Fp: Readonly & Required, "isOdd">>>; + Fp2: mod.IField & { + NONRESIDUE: Fp2; + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + mulByNonresidue: (num: Fp2) => Fp2; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: mod.IField & { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + mul1(num: Fp6, b1: Fp2): Fp6; + mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + mulByFp2(lhs: Fp6, rhs: Fp2): Fp6; + }; + Fp4Square: (a: Fp2, b: Fp2) => { + first: Fp2; + second: Fp2; + }; + Fp12: mod.IField & { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + mulByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; + }; +}; +//# sourceMappingURL=tower.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts.map new file mode 100644 index 0000000..efde5d4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/tower.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.d.ts","sourceRoot":"","sources":["../src/abstract/tower.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAEpC,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAmBvE,MAAM,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,MAAM,MAAM,EAAE,GAAG,MAAM,CAAC;AAGxB,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAC7C,MAAM,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AACzE,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,GAAG,CAAC;IAAC,EAAE,EAAE,GAAG,CAAC;IAAC,EAAE,EAAE,GAAG,CAAA;CAAE,CAAC;AAChD,MAAM,MAAM,IAAI,GAAG;IAAE,EAAE,EAAE,GAAG,CAAC;IAAC,EAAE,EAAE,GAAG,CAAA;CAAE,CAAC;AAExC,MAAM,MAAM,YA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AG;;mBAoJb,GAAG,KAAK,GAAG,KAAG;QAAE,KAAK,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE;;uBAS9C,CAAC,CAAC,EAAE,YAAY,KAAK,IAAI;0BACtB,IAAI,SAAS,MAAM,GAAG,IAAI;oBAChC,IAAI,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG,IAAI;oBACtC,IAAI,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG,IAAI;sBACpC,IAAI,OAAO,GAAG,GAAG,IAAI;uBACpB,IAAI,GAAG,IAAI;+BACH,IAAI,GAAG,IAAI;+BACX,IAAI,GAAG,IAAI;4BACd,IAAI,KAAK,MAAM,GAAG,IAAI;;EAiH7C"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/tower.js b/src/libMPC/node_modules/@noble/curves/abstract/tower.js new file mode 100644 index 0000000..19d2b7d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/tower.js @@ -0,0 +1,498 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.psiFrobenius = psiFrobenius; +exports.tower12 = tower12; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const mod = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +/* +Towered extension fields + +Rather than implementing a massive 12th-degree extension directly, it is more efficient +to build it up from smaller extensions: a tower of extensions. + +For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, +on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + +For more info: "Pairings for beginners" by Costello, section 7.3. +*/ +// 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); +function calcFrobeniusCoefficients(Fp, nonResidue, modulus, degree, num = 1, divisor) { + const _divisor = BigInt(divisor === undefined ? degree : divisor); + const towerModulus = modulus ** BigInt(degree); + const res = []; + for (let i = 0; i < num; i++) { + const a = BigInt(i + 1); + const powers = []; + for (let j = 0, qPower = _1n; j < degree; j++) { + const power = ((a * qPower - a) / _divisor) % towerModulus; + powers.push(Fp.pow(nonResidue, power)); + qPower *= modulus; + } + res.push(powers); + } + return res; +} +// This works same at least for bls12-381, bn254 and bls12-377 +function psiFrobenius(Fp, Fp2, base) { + // Ψ endomorphism + const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3) + const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2) + function psi(x, y) { + // This x10 faster than previous version in bls12-381 + const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X); + const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y); + return [x2, y2]; + } + // Ψ²(P) endomorphism (psi2(x) = psi(psi(x))) + const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3) + // This equals -1, which causes y to be Fp2.neg(y). + // But not sure if there are case when this is not true? + const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/3) + if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) + throw new Error('psiFrobenius: PSI2_Y!==-1'); + function psi2(x, y) { + return [Fp2.mul(x, PSI2_X), Fp2.neg(y)]; + } + // Map points + const mapAffine = (fn) => (c, P) => { + const affine = P.toAffine(); + const p = fn(affine.x, affine.y); + return c.fromAffine({ x: p[0], y: p[1] }); + }; + const G2psi = mapAffine(psi); + const G2psi2 = mapAffine(psi2); + return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y }; +} +function tower12(opts) { + const { ORDER } = opts; + // Fp + const Fp = mod.Field(ORDER); + const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1)); + const FpLegendre = mod.FpLegendre(ORDER); + const Fpdiv2 = Fp.div(Fp.ONE, _2n); // 1/2 + // Fp2 + const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0]; + const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), + }); + const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), + }); + const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; + }; + const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; + }; + const Fp2fromBigTuple = (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }; + const FP2_ORDER = ORDER * ORDER; + const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE); + const Fp2 = { + ORDER: FP2_ORDER, + NONRESIDUE: Fp2Nonresidue, + BITS: (0, utils_js_1.bitLen)(FP2_ORDER), + BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8), + MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (opts.Fp2sqrt) + return opts.Fp2sqrt(num); + // This is generic for all quadratic extensions (Fp2) + const { c0, c1 } = num; + if (Fp.is0(c1)) { + // if c0 is quadratic residue + if (Fp.eql(FpLegendre(Fp, c0), Fp.ONE)) + return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO }); + else + return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) }); + } + const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE))); + let d = Fp.mul(Fp.add(a, c0), Fpdiv2); + const legendre = FpLegendre(Fp, d); + // -1, Quadratic non residue + if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE)) + d = Fp.sub(d, a); + const a0 = Fp.sqrt(d); + const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) }); + if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) + throw new Error('Cannot find square root'); + // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num + const x1 = candidateSqrt; + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue), + mulByB: opts.Fp2mulByB, + fromBigTuple: Fp2fromBigTuple, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), + }; + // Fp6 + const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), + }); + const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), + }); + const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; + }; + const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; + }; + const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 6, 2, 3); + const Fp6 = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: utils_js_1.notImplemented, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + mul1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + mul01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + }; + // Fp12 + const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 12, 1, 6)[0]; + const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), + }); + const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), + }); + const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; + }; + const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB + }; + function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; + } + const Fp12 = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: utils_js_1.notImplemented, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: Fp6.frobeniusMap(lhs.c0, power), + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + mulByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.mulByFp2(c0, rhs), + c1: Fp6.mulByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // Sparse multiplication + mul014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.mul01(c0, o0, o1); + let t1 = Fp6.mul1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + mul034: ({ c0, c1 }, o0, o3, o4) => { + const a = Fp6.create({ + c0: Fp2.mul(c0.c0, o0), + c1: Fp2.mul(c0.c1, o0), + c2: Fp2.mul(c0.c2, o0), + }); + const b = Fp6.mul01(c1, o3, o4); + const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(b), a), + c1: Fp6.sub(e, Fp6.add(a, b)), + }; + }, + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: opts.Fp12cyclotomicSquare, + _cyclotomicExp: opts.Fp12cyclotomicExp, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: opts.Fp12finalExponentiate, + }; + return { Fp, Fp2, Fp6, Fp4Square, Fp12 }; +} +//# sourceMappingURL=tower.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/tower.js.map b/src/libMPC/node_modules/@noble/curves/abstract/tower.js.map new file mode 100644 index 0000000..db9a4d8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/tower.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.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AAC,EAAE,EAAE,EAAE,CAAC;aACvB,CAAC,CAAC;YACH,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;YAChC,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;YAC1D,OAAO;gBACL,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;gBACtC,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;aAC9B,CAAC;QACJ,CAAC;QAED,sDAAsD;QACtD,qCAAqC;QACrC,wDAAwD;QACxD,uCAAuC;QACvC,iBAAiB,EAAE,IAAI,CAAC,oBAAoB;QAC5C,cAAc,EAAE,IAAI,CAAC,iBAAiB;QACtC,uCAAuC;QACvC,uCAAuC;QACvC,iBAAiB,EAAE,IAAI,CAAC,qBAAqB;KAC9C,CAAC;IAEF,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAC3C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts new file mode 100644 index 0000000..f3ce585 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts @@ -0,0 +1,111 @@ +export type Hex = Uint8Array | string; +export type PrivKey = Hex | bigint; +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { + dkLen?: number; + }): any; +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; +export declare function isBytes(a: unknown): a is Uint8Array; +export declare function abytes(item: unknown): void; +export declare function abool(title: string, value: boolean): void; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function numberToHexUnpadded(num: number | bigint): string; +export declare function hexToNumber(hex: string): bigint; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function bytesToNumberLE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array; +export declare function numberToVarBytesBE(n: number | bigint): Uint8Array; +/** + * 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. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export declare function inRange(n: bigint, min: bigint, max: bigint): boolean; +/** + * 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 declare function aInRange(title: string, n: bigint, min: bigint, max: bigint): void; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + */ +export declare function bitSet(n: bigint, pos: number, value: boolean): bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: Uint8Array) => T | undefined; +/** + * 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(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred) => T; +declare const validatorFns: { + readonly bigint: (val: any) => val is bigint; + readonly function: (val: any) => boolean; + readonly boolean: (val: any) => val is boolean; + readonly string: (val: any) => val is string; + readonly stringOrUint8Array: (val: any) => val is string | Uint8Array; + readonly isSafeInteger: (val: any) => boolean; + readonly array: (val: any) => val is any[]; + readonly field: (val: any, object: any) => any; + readonly hash: (val: any) => boolean; +}; +type Validator = keyof typeof validatorFns; +type ValMap> = { + [K in keyof T]?: Validator; +}; +export declare function validateObject>(object: T, validators: ValMap, optValidators?: ValMap): T; +/** + * throws not implemented error + */ +export declare const notImplemented: () => never; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +export declare function memoized(fn: (arg: T, ...args: O) => R): (arg: T, ...args: O) => R; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts.map new file mode 100644 index 0000000..90a0279 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,GAAG,GAAG,UAAU,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,EAChB,MAAM,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,GACjE,CAAC,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CA4C7C;AAID,QAAA,MAAM,YAAY;2BACF,GAAG;6BACD,GAAG;4BACJ,GAAG;2BACJ,GAAG;uCACS,GAAG;kCACR,GAAG;0BACX,GAAG;0BACH,GAAG,UAAU,GAAG;yBACjB,GAAG;CACP,CAAC;AACX,KAAK,SAAS,GAAG,MAAM,OAAO,YAAY,CAAC;AAC3C,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS;CAAE,CAAC;AAG5E,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1D,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EACrB,aAAa,GAAE,MAAM,CAAC,CAAC,CAAM,KAkB9B;AAUD;;GAEG;AACH,eAAO,MAAM,cAAc,aAE1B,CAAC;AAEF;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,SAAS,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,SAE7E,CAAC,WAAW,CAAC,KAAG,CAAC,CAO/B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/utils.js b/src/libMPC/node_modules/@noble/curves/abstract/utils.js new file mode 100644 index 0000000..51f84b4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/utils.js @@ -0,0 +1,362 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.notImplemented = exports.bitMask = void 0; +exports.isBytes = isBytes; +exports.abytes = abytes; +exports.abool = abool; +exports.bytesToHex = bytesToHex; +exports.numberToHexUnpadded = numberToHexUnpadded; +exports.hexToNumber = hexToNumber; +exports.hexToBytes = hexToBytes; +exports.bytesToNumberBE = bytesToNumberBE; +exports.bytesToNumberLE = bytesToNumberLE; +exports.numberToBytesBE = numberToBytesBE; +exports.numberToBytesLE = numberToBytesLE; +exports.numberToVarBytesBE = numberToVarBytesBE; +exports.ensureBytes = ensureBytes; +exports.concatBytes = concatBytes; +exports.equalBytes = equalBytes; +exports.utf8ToBytes = utf8ToBytes; +exports.inRange = inRange; +exports.aInRange = aInRange; +exports.bitLen = bitLen; +exports.bitGet = bitGet; +exports.bitSet = bitSet; +exports.createHmacDrbg = createHmacDrbg; +exports.validateObject = validateObject; +exports.memoized = memoized; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${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(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded 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; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +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. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". 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} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +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; +} +// Compares 2 u8a-s in kinda constant time +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; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Is positive bigint +const isPosBig = (n) => typeof n === 'bigint' && _0n <= n; +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) + */ +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 ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +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]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +/** + * Sets single bit at position. + */ +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('')}`) + */ +const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +exports.bitMask = bitMask; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * 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(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +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) + 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()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([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 = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + 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' }); +/** + * throws not implemented error + */ +const notImplemented = () => { + throw new Error('not implemented'); +}; +exports.notImplemented = notImplemented; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/utils.js.map b/src/libMPC/node_modules/@noble/curves/abstract/utils.js.map new file mode 100644 index 0000000..11b4d0d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":";;;AAkBA,0BAKC;AAED,wBAEC;AAED,sBAGC;AASD,gCAQC;AAED,kDAGC;AAED,kCAIC;AAcD,gCAgBC;AAGD,0CAEC;AACD,0CAGC;AAED,0CAEC;AACD,0CAEC;AAED,gDAEC;AAWD,kCAmBC;AAKD,kCAcC;AAGD,gCAKC;AASD,kCAGC;AAKD,0BAEC;AAOD,4BAQC;AAQD,wBAIC;AAOD,wBAEC;AAKD,wBAEC;AAoBD,wCAgDC;AAmBD,wCAqBC;AAqBD,4BASC;AA/WD,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe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AM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;AACrC,CAAC,CAAC;AAFW,QAAA,cAAc,kBAEzB;AAEF;;;GAGG;AACH,SAAgB,QAAQ,CAAuC,EAA6B;IAC1F,MAAM,GAAG,GAAG,IAAI,OAAO,EAAQ,CAAC;IAChC,OAAO,CAAC,GAAM,EAAE,GAAG,IAAO,EAAK,EAAE;QAC/B,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACzB,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC;QAClC,MAAM,QAAQ,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;QAClC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QACvB,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts new file mode 100644 index 0000000..394182e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts @@ -0,0 +1,258 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { AffinePoint, BasicCurve, Group, GroupConstructor } from './curve.js'; +import * as mod from './modular.js'; +import { CHash, Hex, PrivKey } from './utils.js'; +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +export type BasicWCurve = BasicCurve & { + a: T; + b: T; + allowedPrivateKeyLengths?: readonly number[]; + wrapPrivateKey?: boolean; + endo?: EndomorphismOpts; + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; +type Entropy = Hex | boolean; +export type SignOpts = { + lowS?: boolean; + extraEntropy?: Entropy; + prehash?: boolean; +}; +export type VerOpts = { + lowS?: boolean; + prehash?: boolean; +}; +/** + * ### 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 + */ +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; + msm(points: ProjPointType[], scalars: bigint[]): ProjPointType; +} +export type CurvePointsType = BasicWCurve & { + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; +declare function validatePointOpts(curve: CurvePointsType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: T; + readonly Gy: T; + readonly allowInfinityPoint?: boolean; + readonly a: T; + readonly b: T; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: EndomorphismOpts; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint) | undefined; + readonly toBytes?: ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array) | undefined; + readonly p: bigint; +}>; +export type CurvePointsRes = { + CURVE: ReturnType>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +/** + * 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 declare const DER: { + Err: { + new (m?: string): { + name: string; + message: string; + stack?: string; + }; + }; + _tlv: { + encode: (tag: number, data: string) => string; + decode(tag: number, data: Uint8Array): { + v: Uint8Array; + l: Uint8Array; + }; + }; + _int: { + encode(num: bigint): string; + decode(data: Uint8Array): bigint; + }; + toSig(hex: string | Uint8Array): { + r: bigint; + s: bigint; + }; + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +export declare function weierstrassPoints(opts: CurvePointsType): CurvePointsRes; +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { + r: bigint; + s: bigint; +}; +export type PubKey = Hex | ProjPointType; +export type CurveType = BasicWCurve & { + hash: CHash; + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: EndomorphismOpts; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: HmacFnSync; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; +}>; +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +export declare function weierstrass(curveDef: CurveType): CurveFn; +/** + * 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 declare function SWUFpSqrtRatio(Fp: mod.IField, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +export declare function mapToCurveSimpleSWU(Fp: mod.IField, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts.map b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..937e367 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;A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ACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA4ZxD;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,OAgBnC,CAAC,KAAK,CAAC,KAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAmD7D;AACD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACnC,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EACjB,IAAI,EAAE;IACJ,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,OASU,CAAC,KAAG;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC,EAAE,CAAC,CAAA;CAAE,CA8B9B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js new file mode 100644 index 0000000..6c9ff3b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js @@ -0,0 +1,1145 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DER = void 0; +exports.weierstrassPoints = weierstrassPoints; +exports.weierstrass = weierstrass; +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +const curve_js_1 = require("./curve.js"); +const mod = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + (0, utils_js_1.abool)('lowS', opts.lowS); + if (opts.prehash !== undefined) + (0, utils_js_1.abool)('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * 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 + */ +exports.DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = exports.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 = ut.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 ? ut.numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = exports.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 } = exports.DER; + if (num < _0n) + throw new E('integer: negative integers are not allowed'); + let hex = ut.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 assertion'); + return hex; + }, + decode(data) { + const { Err: E } = exports.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 b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = exports.DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + ut.abytes(data); + 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 } = exports.DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + 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); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = mod.Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return ut.inRange(num, _1n, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (ut.isBytes(key)) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, N); // disabled by default, enabled for BLS + ut.aInRange('private key', num, _1n, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // 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 = (0, utils_js_1.memoized)((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, 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 ax = Fp.mul(x, iz); + const ay = 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: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = (0, utils_js_1.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 wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * 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 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + 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'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * 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. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return (0, curve_js_1.pippenger)(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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.px, Fp.neg(this.py), this.pz); + } + // 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 { px: X1, py: Y1, pz: 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) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * 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 private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + ut.aInRange('scalar', sc, _0n, CURVE.n); + const I = Point.ZERO; + if (sc === _0n) + return I; + if (sc === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * 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, n: N } = CURVE; + ut.aInRange('scalar', scalar, _1n, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // 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) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + (0, utils_js_1.abool)('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + (0, utils_js_1.abool)('isCompressed', isCompressed); + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + (0, utils_js_1.abool)('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!ut.inRange(x, _1n, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N] + ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return exports.DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = ut.isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // 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 = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e)); // check for being bytes + } + const seed = ut.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. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // 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 + const s = modN(ik * modN(m + r * d)); // Not using blinding here + 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 = normalizeS(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 }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. 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, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || ut.isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof exports.DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * 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 + */ +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 + */ +function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // 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, opts.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, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.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, opts.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, opts.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) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js.map b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js.map new file mode 100644 index 0000000..2e0f0c1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":";;;AAuPA,8CA2bC;AAiFD,kCA4ZC;AAWD,wCAmEC;AAKD,kDA6CC;AA/xCD,sEAAsE;AACtE,4DAA4D;AAC5D,yCAQoB;AACpB,oCAAoC;AACpC,iCAAiC;AACjC,yCAA+E;AA4B/E,SAAS,kBAAkB,CAAC,IAAwB;IAClD,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS;QAAE,IAAA,gBAAK,EAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACtD,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;QAAE,IAAA,gBAAK,EAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;AACjE,CAAC;AA4DD,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,IAAI,EAAE,CAAC;QACT,IAAI,CAAC,EAAE,CAA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E,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts b/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts new file mode 100644 index 0000000..fd20783 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts @@ -0,0 +1,3 @@ +import { CurveFn } from './abstract/bls.js'; +export declare const bls12_381: CurveFn; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts.map b/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts.map new file mode 100644 index 0000000..66a6ffa --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bls12-381.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.d.ts","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":"AAGA,OAAO,EAAO,OAAO,EAAE,MAAM,mBAAmB,CAAC;AA2ajD,eAAO,MAAM,SAAS,EAAE,OAqUtB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bls12-381.js b/src/libMPC/node_modules/@noble/curves/bls12-381.js new file mode 100644 index 0000000..43f811b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bls12-381.js @@ -0,0 +1,705 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls12_381 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const bls_js_1 = require("./abstract/bls.js"); +const mod = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +// Types +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const tower_js_1 = require("./abstract/tower.js"); +/* +bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to: +- Construct zk-SNARKs at the 120-bit security +- Efficiently verify N aggregate signatures with 1 pairing and N ec additions: + the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr + +### Summary +1. BLS Relies on Bilinear Pairing (expensive) +2. Private Keys: 32 bytes +3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. + - The signature is a point on the G2 subgroup, which is defined over a finite field + with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +5. The 12 stands for the Embedding degree. + +### Formulas +- `P = pk x G` - public keys +- `S = pk x H(m)` - signing +- `e(P, H(m)) == e(G, S)` - verification using pairings +- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation + +### Compatibility and notes +1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC + Filecoin uses little endian byte arrays for private keys - make sure to reverse byte order. +2. Some projects use G2 for public keys and G1 for signatures. It's called "short signature" +3. Curve security level is about 120 bits as per Barbulescu-Duquesne 2017 + https://hal.science/hal-01534101/file/main.pdf +4. Compatible with specs: +[cfrg-pairing-friendly-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +[cfrg-bls-signature-05](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05), +[RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). +*/ +// 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); +/* +Embedding degree (k): 12 +Seed (X): -15132376222941642752 +Fr: (x⁴-x²+1) +Fp: ((x-1)² ⋅ r(x)/3+x) +(E/Fp): Y²=X³+4 +(Eₜ/Fp²): Y² = X³+4(u+1) (M-type twist) +Ate loop size: X + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-1-u +- Fp¹²[w] = Fp⁶/w²-v + + +TODO: BLS & BN Fp/Fr can be constructed from seed. +*/ +// The BLS parameter x (seed) for BLS12-381. NOTE: it is negative! +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = (0, utils_js_1.bitLen)(BLS_X); +// CURVE FIELDS +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = (0, tower_js_1.tower12)({ + // Order of Fp + ORDER: BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'), + // Finite extension field over irreducible polynominal. + // Fp(u) / (u² - β) where β = -1 + FP2_NONRESIDUE: [_1n, _1n], + Fp2mulByB: ({ c0, c1 }) => { + const t0 = Fp.mul(c0, _4n); // 4 * c0 + const t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + // Fp12 + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if ((0, utils_js_1.bitGet)(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = (0, hash_to_curve_js_1.isogenyMap)(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const { G2psi, G2psi2 } = (0, tower_js_1.psiFrobenius)(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); // 1/(u+1) +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256_1.sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +// Compressed point of infinity +const COMPRESSED_ZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true }); // set compressed & point-at-infinity bits +function parseMask(bytes) { + // Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo. + bytes = bytes.slice(); + const mask = bytes[0] & 224; + const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000) + const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000) + const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000) + bytes[0] &= 31; // clear mask (zero first 3 bits) + return { compressed, infinity, sort, value: bytes }; +} +function setMask(bytes, mask) { + if (bytes[0] & 224) + throw new Error('setMask: non-empty mask'); + if (mask.compressed) + bytes[0] |= 128; + if (mask.infinity) + bytes[0] |= 64; + if (mask.sort) + bytes[0] |= 32; + return bytes; +} +function signatureG1ToRawBytes(point) { + point.assertValidity(); + const isZero = point.equals(exports.bls12_381.G1.ProjectivePoint.ZERO); + const { x, y } = point.toAffine(); + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), { compressed: true, sort }); +} +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(exports.bls12_381.G2.ProjectivePoint.ZERO)) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const sort = Boolean((tmp / Fp.ORDER) & _1n); + const z2 = x0; + return (0, utils_js_1.concatBytes)(setMask((0, utils_js_1.numberToBytesBE)(x1, len), { sort, compressed: true }), (0, utils_js_1.numberToBytesBE)(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +exports.bls12_381 = (0, bls_js_1.bls)({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P + const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(BLS_X).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if (value.length === 48 && compressed) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = (0, utils_js_1.bytesToNumberBE)(value); + // Zero + const x = Fp.create(compressedValue & Fp.MASK); + if (infinity) { + if (x !== _0n) + throw new Error('G1: non-empty compressed point at infinity'); + return { x: _0n, y: _0n }; + } + const right = Fp.add(Fp.pow(x, _3n), Fp.create(exports.bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + if ((y * _2n) / P !== BigInt(sort)) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (value.length === 96 && !compressed) { + // Check if the infinity flag is set + const x = (0, utils_js_1.bytesToNumberBE)(value.subarray(0, Fp.BYTES)); + const y = (0, utils_js_1.bytesToNumberBE)(value.subarray(Fp.BYTES)); + if (infinity) { + if (x !== _0n || y !== _0n) + throw new Error('G1: non-empty point at infinity'); + return exports.bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + } + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), { compressed: true, sort }); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y, Fp.BYTES)); + } + } + }, + ShortSignature: { + fromHex(hex) { + const { infinity, sort, value } = parseMask((0, utils_js_1.ensureBytes)('signatureHex', hex, 48)); + const P = Fp.ORDER; + const compressedValue = (0, utils_js_1.bytesToNumberBE)(value); + // Zero + if (infinity) + return exports.bls12_381.G1.ProjectivePoint.ZERO; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(exports.bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = BigInt(sort); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + const point = exports.bls12_381.G1.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG1ToRawBytes(point); + }, + toHex(point) { + return (0, utils_js_1.bytesToHex)(signatureG1ToRawBytes(point)); + }, + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = BLS_X; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if ((!compressed && !infinity && sort) || // 00100000 + (!compressed && infinity && sort) || // 01100000 + (sort && infinity && compressed) // 11100000 + ) { + throw new Error('Invalid encoding flag: ' + (bytes[0] & 224)); + } + const L = Fp.BYTES; + const slc = (b, from, to) => (0, utils_js_1.bytesToNumberBE)(b.slice(from, to)); + if (value.length === 96 && compressed) { + const b = exports.bls12_381.params.G2b; + const P = Fp.ORDER; + if (infinity) { + // check that all bytes are 0 + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(value, 0, L); + const x_0 = slc(value, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = sort && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (value.length === 192 && !compressed) { + if (infinity) { + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid uncompressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(value, 0, L); + const x0 = slc(value, L, 2 * L); + const y1 = slc(value, 2 * L, 3 * L); + const y0 = slc(value, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + return (0, utils_js_1.concatBytes)(setMask((0, utils_js_1.numberToBytesBE)(x.c1, len), { compressed: true, sort: flag }), (0, utils_js_1.numberToBytesBE)(x.c0, len)); + } + else { + if (isZero) + return (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x1, len), (0, utils_js_1.numberToBytesBE)(x0, len), (0, utils_js_1.numberToBytesBE)(y1, len), (0, utils_js_1.numberToBytesBE)(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + const { infinity, sort, value } = parseMask((0, utils_js_1.ensureBytes)('signatureHex', hex)); + const P = Fp.ORDER; + const half = value.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = (0, utils_js_1.bytesToNumberBE)(value.slice(0, half)); + const z2 = (0, utils_js_1.bytesToNumberBE)(value.slice(half)); + // Indicates the infinity point + if (infinity) + return exports.bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), exports.bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = BigInt(sort); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = exports.bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return (0, utils_js_1.bytesToHex)(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + xNegative: true, + twistType: 'multiplicative', + }, + htfDefaults, + hash: sha256_1.sha256, + randomBytes: utils_1.randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bls12-381.js.map b/src/libMPC/node_modules/@noble/curves/bls12-381.js.map new file mode 100644 index 0000000..02196ad --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAAkD;AAClD,8CAAiD;AACjD,6CAA6C;AAC7C,kDAS6B;AAC7B,QAAQ;AACR,kEAAyD;AACzD,8DAA4F;AAC5F,kDAA4D;AAG5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BE;AAEF,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E,CAAC,KAAK,EAAE,gDAAgD;QAC7D,SAAS,EAAE,IAAI;QACf,SAAS,EAAE,gBAAgB;KAC5B;IACD,WAAW;IACX,IAAI,EAAE,eAAM;IACZ,WAAW,EAAX,mBAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bn254.d.ts b/src/libMPC/node_modules/@noble/curves/bn254.d.ts new file mode 100644 index 0000000..4f7252a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bn254.d.ts @@ -0,0 +1,13 @@ +import { CurveFn } from './abstract/bls.js'; +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings. + */ +export declare const bn254: CurveFn; +/** + * bn254 weierstrass curve with ECDSA. + * This is very rare and probably not used anywhere. + * Instead, you should use G1 / G2, defined above. + */ +export declare const bn254_weierstrass: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bn254.d.ts.map b/src/libMPC/node_modules/@noble/curves/bn254.d.ts.map new file mode 100644 index 0000000..87af386 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":"AAKA,OAAO,EAAO,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAiJjD;;;GAGG;AACH,eAAO,MAAM,KAAK,EAAE,OAkElB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,6CAS5B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bn254.js b/src/libMPC/node_modules/@noble/curves/bn254.js new file mode 100644 index 0000000..0a82628 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bn254.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bn254_weierstrass = exports.bn254 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const utils_1 = require("@noble/hashes/utils"); +const bls_js_1 = require("./abstract/bls.js"); +const modular_js_1 = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +const tower_js_1 = require("./abstract/tower.js"); +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _6n = BigInt(6); +/* +bn254, previously known as alt_bn_128, when it had 128-bit security. +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/execution-specs/blob/master/src/ethereum/crypto/alt_bn128.py +- Points are encoded differently in different implementations +*/ +/* +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v +*/ +const BN_X = BigInt('4965661367192848881'); +const BN_X_LEN = (0, utils_js_1.bitLen)(BN_X); +const SIX_X_SQUARED = _6n * BN_X ** _2n; +// Finite field over r. It's for convenience and is not used in the code below. +const Fr = (0, modular_js_1.Field)(BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617')); +// Fp2.div(Fp2.mul(Fp2.ONE, _3n), Fp2.NONRESIDUE) +const Fp2B = { + c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'), + c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'), +}; +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = (0, tower_js_1.tower12)({ + ORDER: BigInt('21888242871839275222246405745257275088696311157297823662689037894645226208583'), + FP2_NONRESIDUE: [BigInt(9), _1n], + Fp2mulByB: (num) => Fp2.mul(num, Fp2B), + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BN_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if ((0, utils_js_1.bitGet)(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const powMinusX = (num) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X)); + const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num)); + const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0); + const y1 = Fp12._cyclotomicSquare(powMinusX(r)); + const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1); + const y4 = powMinusX(y2); + const y6 = powMinusX(Fp12._cyclotomicSquare(y4)); + const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2)); + const y9 = Fp12.mul(y8, y1); + return Fp12.mul(Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), Fp12.mul(Fp12.frobeniusMap(y8, 2), Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r)))); + }, +}); +// END OF CURVE FIELDS +const { G2psi, psi } = (0, tower_js_1.psiFrobenius)(Fp, Fp2, Fp2.NONRESIDUE); +/* +No hashToCurve for now (and signatures): + +- RFC 9380 doesn't mention bn254 and doesn't provide test vectors +- Overall seems like nobody is using BLS signatures on top of bn254 +- Seems like it can utilize SVDW, which is not implemented yet +*/ +const htfDefaults = Object.freeze({ + // DST: a domain separation tag defined in section 2.2.5 + DST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + p: Fp.ORDER, + m: 2, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}); +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings. + */ +exports.bn254 = (0, bls_js_1.bls)({ + // Fields + fields: { Fp, Fp2, Fp6, Fp12, Fr }, + G1: { + Fp, + h: BigInt(1), + Gx: BigInt(1), + Gy: BigInt(2), + a: Fp.ZERO, + b: _3n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: utils_js_1.notImplemented, + fromBytes: utils_js_1.notImplemented, + toBytes: utils_js_1.notImplemented, + ShortSignature: { + fromHex: utils_js_1.notImplemented, + toRawBytes: utils_js_1.notImplemented, + toHex: utils_js_1.notImplemented, + }, + }, + G2: { + Fp: Fp2, + // cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1 + h: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + Gx: Fp2.fromBigTuple([ + BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'), + BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'), + BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'), + ]), + a: Fp2.ZERO, + b: Fp2B, + hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P + mapToCurve: utils_js_1.notImplemented, + fromBytes: utils_js_1.notImplemented, + toBytes: utils_js_1.notImplemented, + Signature: { + fromHex: utils_js_1.notImplemented, + toRawBytes: utils_js_1.notImplemented, + toHex: utils_js_1.notImplemented, + }, + }, + params: { + ateLoopSize: BN_X * _6n + _2n, + r: Fr.ORDER, + xNegative: false, + twistType: 'divisive', + }, + htfDefaults, + hash: sha256_1.sha256, + randomBytes: utils_1.randomBytes, + postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => { + const q = psi(Qx, Qy); + ({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1])); + const q2 = psi(q[0], q[1]); + pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1])); + }, +}); +/** + * bn254 weierstrass curve with ECDSA. + * This is very rare and probably not used anywhere. + * Instead, you should use G1 / G2, defined above. + */ +exports.bn254_weierstrass = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(3), + Fp, + n: BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/bn254.js.map b/src/libMPC/node_modules/@noble/curves/bn254.js.map new file mode 100644 index 0000000..212f738 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,yDAA6C;AAC7C,8DAAwD;AACxD,+CAAkD;AAClD,8CAAiD;AACjD,sDAA8C;AAC9C,kDAAqE;AACrE,kDAA4D;AAG5D,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,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AC;QAC3B,QAAQ,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,CAAC;CACF,CAAC,CAAC;AAEH;;;;GAIG;AACU,QAAA,iBAAiB,GAAG,IAAA,4BAAW,EAAC;IAC3C,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE;IACF,CAAC,EAAE,MAAM,CAAC,+EAA+E,CAAC;IAC1F,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed25519.d.ts b/src/libMPC/node_modules/@noble/curves/ed25519.d.ts new file mode 100644 index 0000000..6172a96 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed25519.d.ts @@ -0,0 +1,81 @@ +import { AffinePoint, Group } from './abstract/curve.js'; +import { CurveFn, ExtPointType } from './abstract/edwards.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Hex } from './abstract/utils.js'; +export declare const ED25519_TORSION_SUBGROUP: string[]; +/** + * ed25519 curve with EdDSA signatures. + */ +export declare const ed25519: CurveFn; +export declare const ed25519ctx: CurveFn; +export declare const ed25519ph: CurveFn; +export declare const x25519: import("./abstract/montgomery.js").CurveFn; +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export declare function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class RistPoint implements Group { + private readonly ep; + static BASE: RistPoint; + static ZERO: RistPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): RistPoint; + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint; + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: RistPoint): boolean; + add(other: RistPoint): RistPoint; + subtract(other: RistPoint): RistPoint; + multiply(scalar: bigint): RistPoint; + multiplyUnsafe(scalar: bigint): RistPoint; + double(): RistPoint; + negate(): RistPoint; +} +export declare const RistrettoPoint: typeof RistPoint; +export declare const hashToRistretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export declare const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed25519.d.ts.map b/src/libMPC/node_modules/@noble/curves/ed25519.d.ts.map new file mode 100644 index 0000000..5c50df6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed25519.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAoC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG7F,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AA0E7B,eAAO,MAAM,wBAAwB,UASpC,CAAC;AA8BF;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,OAAmE,CAAC;AAY1F,eAAO,MAAM,UAAU,SAIhB,CAAC;AACR,eAAO,MAAM,SAAS,SAMhB,CAAC;AAEP,eAAO,MAAM,MAAM,4CAeZ,CAAC;AAER;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAIlE;AACD,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AAE1D;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,UAAU,GAAG,UAAU,CAG3E;AA0FD,eAAO,MAAM,WAAW,qGAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,qGAA8C,CAAC;AAiCzE,KAAK,aAAa,GAAG,YAAY,CAAC;AA0BlC;;;;;;GAMG;AACH,cAAM,SAAU,YAAW,KAAK,CAAC,SAAS,CAAC;IAK7B,OAAO,CAAC,QAAQ,CAAC,EAAE;IAJ/B,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC;IACvB,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC;gBAGM,EAAE,EAAE,aAAa;IAE9C,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC;IAIzC;;;;;;OAMG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,SAAS;IASvC;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,SAAS;IA2BnC;;;OAGG;IACH,UAAU,IAAI,UAAU;IA4BxB,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAKlB,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO;IAWjC,GAAG,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS;IAKhC,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS;IAKrC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAInC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAIzC,MAAM,IAAI,SAAS;IAInB,MAAM,IAAI,SAAS;CAGpB;AACD,eAAO,MAAM,cAAc,kBAIvB,CAAC;AAGL,eAAO,MAAM,kBAAkB,QAAS,UAAU,WAAW,YAAY,cAMxE,CAAC;AACF,eAAO,MAAM,oBAAoB,QAPO,UAAU,WAAW,YAAY,cAOnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed25519.js b/src/libMPC/node_modules/@noble/curves/ed25519.js new file mode 100644 index 0000000..98301b4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed25519.js @@ -0,0 +1,449 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_ristretto255 = exports.hashToRistretto255 = exports.RistrettoPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomery = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = exports.ED25519_TORSION_SUBGROUP = void 0; +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomeryPriv = edwardsToMontgomeryPriv; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const utils_js_1 = require("./abstract/utils.js"); +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _5n = BigInt(5), _8n = BigInt(8); +function ed25519_pow_2_252_3(x) { + // prettier-ignore + const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = ((0, modular_js_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = ((0, modular_js_1.pow2)(b4, _1n, P) * x) % P; // x^31 + const b10 = ((0, modular_js_1.pow2)(b5, _5n, P) * b5) % P; + const b20 = ((0, modular_js_1.pow2)(b10, _10n, P) * b10) % P; + const b40 = ((0, modular_js_1.pow2)(b20, _20n, P) * b20) % P; + const b80 = ((0, modular_js_1.pow2)(b40, _40n, P) * b40) % P; + const b160 = ((0, modular_js_1.pow2)(b80, _80n, P) * b80) % P; + const b240 = ((0, modular_js_1.pow2)(b160, _80n, P) * b80) % P; + const b250 = ((0, modular_js_1.pow2)(b240, _10n, P) * b10) % P; + const pow_p_5_8 = ((0, modular_js_1.pow2)(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = (0, modular_js_1.mod)(v * v * v, P); // v³ + const v7 = (0, modular_js_1.mod)(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = (0, modular_js_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = (0, modular_js_1.mod)(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = (0, modular_js_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === (0, modular_js_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === (0, modular_js_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = (0, modular_js_1.mod)(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +exports.ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = /* @__PURE__ */ (() => (0, modular_js_1.Field)(ED25519_P, undefined, true))(); +const ed25519Defaults = /* @__PURE__ */ (() => ({ + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: _8n, + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}))(); +/** + * ed25519 curve with EdDSA signatures. + */ +exports.ed25519 = (() => (0, edwards_js_1.twistedEdwards)(ed25519Defaults))(); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +exports.ed25519ctx = (() => (0, edwards_js_1.twistedEdwards)({ + ...ed25519Defaults, + domain: ed25519_domain, +}))(); +exports.ed25519ph = (() => (0, edwards_js_1.twistedEdwards)(Object.assign({}, ed25519Defaults, { + domain: ed25519_domain, + prehash: sha512_1.sha512, +})))(); +exports.x25519 = (() => (0, montgomery_js_1.montgomery)({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return (0, modular_js_1.mod)((0, modular_js_1.pow2)(pow_p_5_8, _3n, P) * b2, P); + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1 +const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1) +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic + const ELL2_J = BigInt(486662); + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => (0, modular_js_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => exports.ed25519.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!(0, modular_js_1.isNegativeLE)(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new exports.ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(exports.ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHex', hex, 32); + const { a, d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 32), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || (0, modular_js_1.isNegativeLE)(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new exports.ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if ((0, modular_js_1.isNegativeLE)(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if ((0, modular_js_1.isNegativeLE)(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 32); // 11 + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } + double() { + return new RistPoint(this.ep.double()); + } + negate() { + return new RistPoint(this.ep.negate()); + } +} +exports.RistrettoPoint = (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(exports.ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(exports.ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +const hashToRistretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xmd)(msg, DST, 64, sha512_1.sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hashToRistretto255 = hashToRistretto255; +exports.hash_to_ristretto255 = exports.hashToRistretto255; // legacy +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed25519.js.map b/src/libMPC/node_modules/@noble/curves/ed25519.js.map new file mode 100644 index 0000000..8732fcb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":";;;AAsLA,wDAIC;AAUD,0DAGC;AAvMD,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAE5E,sDAA8E;AAC9E,kEAA6F;AAC7F,sDAAmF;AACnF,4DAAsD;AACtD,kDAO6B;AAE7B;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,CAC5C,+EAA+E,CAChF,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvC,SAAS,mBAAmB,CAAC,CAAS;IACpC,kBAAkB;IAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,C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,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,eAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,6EAA6E;AACtE,MAAM,kBAAkB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC3E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,IAAA,qCAAkB,EAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,eAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,kBAAkB,sBAM7B;AACW,QAAA,oBAAoB,GAAG,0BAAkB,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed448.d.ts b/src/libMPC/node_modules/@noble/curves/ed448.d.ts new file mode 100644 index 0000000..2c34043 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed448.d.ts @@ -0,0 +1,67 @@ +import { AffinePoint, Group } from './abstract/curve.js'; +import { ExtPointType } from './abstract/edwards.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Hex } from './abstract/utils.js'; +export declare const ed448: import("./abstract/edwards.js").CurveFn; +export declare const ed448ph: import("./abstract/edwards.js").CurveFn; +export declare const x448: import("./abstract/montgomery.js").CurveFn; +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class DcfPoint implements Group { + private readonly ep; + static BASE: DcfPoint; + static ZERO: DcfPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): DcfPoint; + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex: Hex): DcfPoint; + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: Hex): DcfPoint; + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: DcfPoint): boolean; + add(other: DcfPoint): DcfPoint; + subtract(other: DcfPoint): DcfPoint; + multiply(scalar: bigint): DcfPoint; + multiplyUnsafe(scalar: bigint): DcfPoint; + double(): DcfPoint; + negate(): DcfPoint; +} +export declare const DecafPoint: typeof DcfPoint; +export declare const hashToDecaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export declare const hash_to_decaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export {}; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed448.d.ts.map b/src/libMPC/node_modules/@noble/curves/ed448.d.ts.map new file mode 100644 index 0000000..f5ba2bf --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAoC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG7F,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAsH7B,eAAO,MAAM,KAAK,yCAA4C,CAAC;AAE/D,eAAO,MAAM,OAAO,yCAAyE,CAAC;AAE9F,eAAO,MAAM,IAAI,4CAgBV,CAAC;AAER;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAIlF;AAED,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AA8F1D,eAAO,MAAM,WAAW,qGAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,qGAA8C,CAAC;AA2BzE,KAAK,aAAa,GAAG,YAAY,CAAC;AAiClC;;;;;;GAMG;AACH,cAAM,QAAS,YAAW,KAAK,CAAC,QAAQ,CAAC;IAK3B,OAAO,CAAC,QAAQ,CAAC,EAAE;IAJ/B,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;IACtB,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;gBAGO,EAAE,EAAE,aAAa;IAE9C,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC;IAIzC;;;;;;OAMG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,QAAQ;IAStC;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,QAAQ;IA8BlC;;;OAGG;IACH,UAAU,IAAI,UAAU;IAoBxB,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAMlB,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO;IAShC,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,QAAQ;IAK9B,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,QAAQ;IAKnC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ;IAIlC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ;IAIxC,MAAM,IAAI,QAAQ;IAIlB,MAAM,IAAI,QAAQ;CAGnB;AAED,eAAO,MAAM,UAAU,iBAMnB,CAAC;AAGL,eAAO,MAAM,cAAc,QAAS,UAAU,WAAW,YAAY,aAMpE,CAAC;AACF,eAAO,MAAM,gBAAgB,QAPO,UAAU,WAAW,YAAY,aAOvB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed448.js b/src/libMPC/node_modules/@noble/curves/ed448.js new file mode 100644 index 0000000..e17931a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed448.js @@ -0,0 +1,406 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_decaf448 = exports.hashToDecaf448 = exports.DecafPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomery = exports.x448 = exports.ed448ph = exports.ed448 = void 0; +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha3_1 = require("@noble/hashes/sha3"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const utils_js_1 = require("./abstract/utils.js"); +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 114 })); +const shake256_64 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b222 = ((0, modular_js_1.pow2)(b220, _2n, P) * b2) % P; + const b223 = ((0, modular_js_1.pow2)(b222, _1n, P) * x) % P; + return ((0, modular_js_1.pow2)(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = (0, modular_js_1.mod)(u * u * v, P); // u²v + const u3v = (0, modular_js_1.mod)(u2v * u, P); // u³v + const u5v3 = (0, modular_js_1.mod)(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = (0, modular_js_1.mod)(u3v * root, P); + // Verify that root is exists + const x2 = (0, modular_js_1.mod)(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: (0, modular_js_1.mod)(x2 * v, P) === u, value: x }; +} +const Fp = (0, modular_js_1.Field)(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +exports.ed448 = (0, edwards_js_1.twistedEdwards)(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +exports.ed448ph = (0, edwards_js_1.twistedEdwards)({ ...ED448_DEF, prehash: shake256_64 }); +exports.x448 = (() => (0, montgomery_js_1.montgomery)({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = (0, modular_js_1.pow2)(Pminus3div4, BigInt(2), P); + return (0, modular_js_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: sha3_1.shake256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertDcfPoint(other) { + if (!(other instanceof DcfPoint)) + throw new Error('DecafPoint expected'); +} +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes448ToNumberLE = (bytes) => exports.ed448.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_448B); +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0) { + const { d } = exports.ed448.CURVE; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + let v_prime = v; // 5 + if (!was_square) + v_prime = mod(r0 * v); + let sgn = _1n; // 6 + if (!was_square) + sgn = mod(-_1n); + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if ((0, modular_js_1.isNegativeLE)(s, P)) + s_abs = mod(-s); + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new exports.ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint { + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new DcfPoint(exports.ed448.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('decafHex', hex, 56); + const { d } = exports.ed448.CURVE; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 56), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if ((0, modular_js_1.isNegativeLE)(u3, P)) + u3 = mod(-u3); + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + if (!isValid) + throw new Error(emsg); + return new DcfPoint(new exports.ed448.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes() { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = exports.ed448.CURVE.Fp.ORDER; + const mod = exports.ed448.CURVE.Fp.create; + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if ((0, modular_js_1.isNegativeLE)(ratio, P)) + ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 56); + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other) { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + add(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new DcfPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } + double() { + return new DcfPoint(this.ep.double()); + } + negate() { + return new DcfPoint(this.ep.negate()); + } +} +exports.DecafPoint = (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) + DcfPoint.BASE = new DcfPoint(exports.ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) + DcfPoint.ZERO = new DcfPoint(exports.ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +const hashToDecaf448 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xof)(msg, DST, 112, 224, sha3_1.shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hashToDecaf448 = hashToDecaf448; +exports.hash_to_decaf448 = exports.hashToDecaf448; // legacy +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/ed448.js.map b/src/libMPC/node_modules/@noble/curves/ed448.js.map new file mode 100644 index 0000000..0117953 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":";;;AAmKA,wDAIC;AAvKD,sEAAsE;AACtE,6CAA8C;AAC9C,+CAA6F;AAE7F,sDAAqE;AACrE,kEAA6F;AAC7F,sDAAuE;AACvE,4DAAsD;AACtD,kDAO6B;AAE7B;;;;;;GAMG;AAEH,MAAM,YAAY,GAAG,IAAA,uBAAe,EAAC,GAAG,EAAE,CAAC,eAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AAC5E,MAAM,WAAW,GAAG,IAAA,uBAAe,EAAC,GAAG,EAAE,CAAC,eAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1E,MAAM,MAAM,GAAG,MAAM,CACnB,yIAAyI,CAC1I,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC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,CAAC,QAAQ,CAAC,IAAI;QAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,QAAQ,CAAC,aAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC3E,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC,EAAE,CAAC;AAEL,yEAAyE;AAClE,MAAM,cAAc,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IACvE,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,IAAA,qCAAkB,EAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,eAAQ,CAAC,CAAC;IACvE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB;AACW,QAAA,gBAAgB,GAAG,sBAAc,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts new file mode 100644 index 0000000..39244c6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts @@ -0,0 +1,62 @@ +import { randomBytes } from '@noble/hashes/utils'; +import { CHash } from './abstract/utils.js'; +import { CurveType } from './abstract/weierstrass.js'; +export declare function getHash(hash: CHash): { + hash: CHash; + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array; + randomBytes: typeof randomBytes; +}; +type CurveDef = Readonly>; +export declare function createCurve(curveDef: CurveDef, defHash: CHash): Readonly<{ + create: (hash: CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export {}; +//# sourceMappingURL=_shortw_utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts.map new file mode 100644 index 0000000..dfa9b12 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AAGnE,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK;;gBAGnB,UAAU,WAAW,UAAU,EAAE;;EAGhD;AAED,KAAK,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAC3E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK;mBACtC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAG01zB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;GADzi2B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js new file mode 100644 index 0000000..cc93e45 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js @@ -0,0 +1,17 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass } from './abstract/weierstrass.js'; +// connects noble-curves to noble-hashes +export function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +export function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js.map b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js.map new file mode 100644 index 0000000..c639439 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAE/D,OAAO,EAAa,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAEnE,wCAAwC;AACxC,MAAM,UAAU,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW;KACZ,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts new file mode 100644 index 0000000..02e1ff2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts @@ -0,0 +1,125 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +import { Hex, PrivKey, CHash } from './utils.js'; +import { MapToCurve, Opts as HTFOpts, htfBasicOpts, createHasher } from './hash-to-curve.js'; +import { CurvePointsType, ProjPointType as ProjPointType, CurvePointsRes } from './weierstrass.js'; +import type { Fp2, Fp6, Fp12, Fp2Bls, Fp12Bls } from './tower.js'; +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two main ways to use it: + * 1. Fp for short private keys, Fp₂ for signatures + * 2. Fp for short signatures, Fp₂ for private keys + **/ +type Fp = bigint; +export type TwistType = 'multiplicative' | 'divisive'; +export type ShortSignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type CurveType = { + G1: Omit, 'n'> & { + ShortSignature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + }; + params: { + ateLoopSize: bigint; + xNegative: boolean; + r: bigint; + twistType: TwistType; + }; + htfDefaults: HTFOpts; + hash: CHash; + randomBytes: (bytesLength?: number) => Uint8Array; + postPrecompute?: (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2, pointAdd: (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => { + Rx: Fp2; + Ry: Fp2; + Rz: Fp2; + }) => void; +}; +type PrecomputeSingle = [Fp2, Fp2, Fp2][]; +type Precompute = PrecomputeSingle[]; +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + getPublicKeyForShortSignatures: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + signShortSignature: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + verify: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType, htfOpts?: htfBasicOpts) => boolean; + verifyShortSignature: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType, htfOpts?: htfBasicOpts) => boolean; + verifyBatch: (signature: Hex | ProjPointType, messages: (Hex | ProjPointType)[], publicKeys: (Hex | ProjPointType)[], htfOpts?: htfBasicOpts) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + aggregateShortSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + pairingBatch: (pairs: { + g1: ProjPointType; + g2: ProjPointType; + }[], withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + ShortSignature: ShortSignatureCoder; + params: { + ateLoopSize: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: ProjPointType) => Precompute; + }; +}; +export declare function bls(CURVE: CurveType): CurveFn; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts.map new file mode 100644 index 0000000..2797dc5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAGtE,OAAO,EAAE,MAAM,EAAoC,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAyB,MAAM,YAAY,CAAC;AAExE,OAAO,EACL,UAAU,EAAE,IAAI,IAAI,OAAO,EAAuB,YAAY,EAC9D,YAAY,EACb,MAAM,oBAAo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AAO,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/D,SAAS,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC;IAC/B,cAAc,EAAE,mBAAmB,CAAC,EAAE,CAAC,CAAC;IACxC,MAAM,EAAE;QACN,WAAW,EAAE,MAAM,CAAC;QACpB,CAAC,EAAE,MAAM,CAAC;QACV,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,GAAG,CAAC;KACV,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;QACf,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QACjB,IAAI,EAAE,OAAO,CAAC;QACd,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;KACpB,CAAC;IACF,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,sBAAsB,EAAE,CAAC,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,KAAK,UAAU,CAAC;KAC/D,CAAC;CACH,CAAC;AAgBF,wBAAgB,GAAG,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAsX7C"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js new file mode 100644 index 0000000..7f2a61f --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js @@ -0,0 +1,337 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. +// TODO: import { AffinePoint } from './curve.js'; +import { getMinHashLength, mapHashToField } from './modular.js'; +import { ensureBytes, memoized } from './utils.js'; +// prettier-ignore +import { createHasher } from './hash-to-curve.js'; +import { weierstrassPoints, } from './weierstrass.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// Not used with BLS12-381 (no sequential `11` in X). Useful for other curves. +function NAfDecomposition(a) { + const res = []; + // a>1 because of marker bit + for (; a > _1n; a >>= _1n) { + if ((a & _1n) === _0n) + res.unshift(0); + else if ((a & _3n) === _3n) { + res.unshift(-1); + a += _1n; + } + else + res.unshift(1); + } + return res; +} +export function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_IS_NEGATIVE = CURVE.params.xNegative; + const TWIST = CURVE.params.twistType; + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + // Applies sparse multiplication as line function + let lineFunction; + if (TWIST === 'multiplicative') { + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); + } + else if (TWIST === 'divisive') { + // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of + // precompute calculations. + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); + } + else + throw new Error('bls: unknown twist type'); + const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n)); + function pointDouble(ell, Rx, Ry, Rz) { + const t0 = Fp2.sqr(Ry); // Ry² + const t1 = Fp2.sqr(Rz); // Rz² + const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + const t3 = Fp2.mul(t2, _3n); // 3 * T2 + const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + const c0 = Fp2.sub(t2, t0); // T2 - T0 (i) + const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx² + const c2 = Fp2.neg(t4); // -T4 (-h) + ell.push([c0, c1, c2]); + Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + return { Rx, Ry, Rz }; + } + function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) { + // Addition + const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy + const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry + const c2 = t1; // == Rx - Qx * Rz + ell.push([c0, c1, c2]); + const t2 = Fp2.sqr(t1); // T1² + const t3 = Fp2.mul(t2, t1); // T2 * T1 + const t4 = Fp2.mul(t2, Rx); // T2 * Rx + const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + return { Rx, Ry, Rz }; + } + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine + // add + double in windowed precomputes here, otherwise it would be single op (since X is static) + const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize); + const calcPairingPrecomputes = memoized((point) => { + const p = point; + const { x, y } = p.toAffine(); + // prettier-ignore + const Qx = x, Qy = y, negQy = Fp2.neg(y); + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; + const ell = []; + for (const bit of ATE_NAF) { + const cur = []; + ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); + if (bit) + ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); + ell.push(cur); + } + if (CURVE.postPrecompute) { + const last = ell[ell.length - 1]; + CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); + } + return ell; + }); + function millerLoopBatch(pairs, withFinalExponent = false) { + let f12 = Fp12.ONE; + if (pairs.length) { + const ellLen = pairs[0][0].length; + for (let i = 0; i < ellLen; i++) { + f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings + // NOTE: we apply multiple pairings in parallel here + for (const [ell, Px, Py] of pairs) { + for (const [c0, c1, c2] of ell[i]) + f12 = lineFunction(c0, c1, c2, f12, Px, Py); + } + } + } + if (BLS_X_IS_NEGATIVE) + f12 = Fp12.conjugate(f12); + return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; + } + // Calculates product of multiple pairings + // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))` + function pairingBatch(pairs, withFinalExponent = true) { + const res = []; + // This cache precomputed toAffine for all points + G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1)); + G2.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2)); + for (const { g1, g2 } of pairs) { + if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + // This uses toAffine inside + g1.assertValidity(); + g2.assertValidity(); + const Qa = g1.toAffine(); + res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]); + } + return millerLoopBatch(res, withFinalExponent); + } + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + return pairingBatch([{ g1: Q, g2: P }], withFinalExponent); + } + const utils = { + randomPrivateKey: () => { + const length = getMinHashLength(Fr.ORDER); + return mapHashToField(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + const { ShortSignature } = CURVE.G1; + const { Signature } = CURVE.G2; + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP1Hash(point, htfOpts) { + return point instanceof G1.ProjectivePoint + ? point + : G1.hashToCurve(ensureBytes('point', point), htfOpts); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve(ensureBytes('point', point), htfOpts); + } + // Multiplies generator (G1) by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + // Multiplies generator (G2) by private key. + // P = pk x G + function getPublicKeyForShortSignatures(privateKey) { + return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + function signShortSignature(message, privateKey, htfOpts) { + const msgPoint = normP1Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G1.ProjectivePoint) + return sigPoint; + return ShortSignature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + const exp = pairingBatch([ + { g1: P.negate(), g2: Hm }, // ePHM = pairing(P.negate(), Hm, false); + { g1: G, g2: S }, // eGS = pairing(G, S, false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(S, G) == e(H(m), P) + function verifyShortSignature(signature, message, publicKey, htfOpts) { + const P = normP2(publicKey); + const Hm = normP1Hash(message, htfOpts); + const G = G2.ProjectivePoint.BASE; + const S = normP1(signature); + const exp = pairingBatch([ + { g1: Hm, g2: P }, // eHmP = pairing(Hm, P, false); + { g1: S, g2: G.negate() }, // eSG = pairing(S, G.negate(), false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + function aggregateShortSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return ShortSignature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, + // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead? + messages, publicKeys, htfOpts) { + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + // NOTE: this works only for exact same object + const messagePubKeyMap = new Map(); + for (let i = 0; i < nPublicKeys.length; i++) { + const pub = nPublicKeys[i]; + const msg = nMessages[i]; + let keys = messagePubKeyMap.get(msg); + if (keys === undefined) { + keys = []; + messagePubKeyMap.set(msg, keys); + } + keys.push(pub); + } + const paired = []; + try { + for (const [msg, keys] of messagePubKeyMap) { + const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg)); + paired.push({ g1: groupPublicKey, g2: msg }); + } + paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig }); + return Fp12.eql(pairingBatch(paired), Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + getPublicKeyForShortSignatures, + sign, + signShortSignature, + verify, + verifyBatch, + verifyShortSignature, + aggregatePublicKeys, + aggregateSignatures, + aggregateShortSignatures, + millerLoopBatch, + pairing, + pairingBatch, + G1, + G2, + Signature, + ShortSignature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + ateLoopSize: CURVE.params.ateLoopSize, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js.map new file mode 100644 index 0000000..3299a94 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,kDAAkD;AAClD,OAAO,EAAU,gBAAgB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACxE,OAAO,EAAuB,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACxE,kBAAkB;AAClB,OAAO,EAEL,YAAY,EACb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIL,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAqB1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAkIzE,8EAA8E;AAC9E,SAAS,gBAAgB,CAAC,CAAS;IACjC,MAAM,GAAG,GAAG,EAAE,CAAC;IACf,4BAA4B;IAC5B,OAAO,CAAC,GAAG,GAAG,EAAE,CAAC,KAAK,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,KAAK,GAAG;YAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;aACjC,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC;YAC3B,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YAChB,CAAC,IAAI,GAAG,CAAC;QACX,CAAC;;YAAM,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,GAAG,CAAC,KAAgB;IAClC,8EAA8E;IAC9E,MAA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P,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAE1C,OAAO;QACL,YAAY;QACZ,8BAA8B;QAC9B,IAAI;QACJ,kBAAkB;QAClB,MAAM;QACN,WAAW;QACX,oBAAoB;QACpB,mBAAmB;QACnB,mBAAmB;QACnB,wBAAwB;QACxB,eAAe;QACf,OAAO;QACP,YAAY;QACZ,EAAE;QACF,EAAE;QACF,SAAS;QACT,cAAc;QACd,MAAM,EAAE;YACN,EAAE;YACF,EAAE;YACF,GAAG;YACH,GAAG;YACH,IAAI;SACL;QACD,MAAM,EAAE;YACN,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,WAAW;YACrC,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts new file mode 100644 index 0000000..79fd78a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts @@ -0,0 +1,83 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type AffinePoint = { + x: T; + y: T; +} & { + z?: never; + t?: never; +}; +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; +export declare function wNAF>(c: GroupConstructor, bits: number): { + constTimeNegate: (condition: boolean, item: T) => T; + unsafeLadder(elm: T, n: bigint): T; + /** + * 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. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[]; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { + p: T; + f: T; + }; + wNAFCached(P: T, n: bigint, transform: Mapper): { + p: T; + f: T; + }; + setWindowSize(P: T, W: number): void; +}; +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with 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 field 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 private keys / bigints) + */ +export declare function pippenger>(c: GroupConstructor, field: IField, points: T[], scalars: bigint[]): T; +export type BasicCurve = { + Fp: IField; + n: bigint; + nBitLength?: number; + nByteLength?: number; + h: bigint; + hEff?: bigint; + Gx: T; + Gy: T; + allowInfinityPoint?: boolean; +}; +export declare function validateBasic(curve: BasicCurve & T): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; +} & BasicCurve & T & { + p: bigint; +}>; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.d.ts.map new file mode 100644 index 0000000..5a279cb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ab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ACK,MAAM,eAAe,CAAC,EAAE,KAAK,MAAM,GAAG;QAAE,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC,EAAE,CAAC,CAAA;KAAE;kBAsD9C,CAAC,KAAK,MAAM,aAAa,MAAM,CAAC,CAAC,CAAC,GAAG;QAAE,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC,EAAE,CAAC,CAAA;KAAE;qBAchD,CAAC,KAAK,MAAM;EAMhC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,EAC1C,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,EACtB,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EACrB,MAAM,EAAE,CAAC,EAAE,EACX,OAAO,EAAE,MAAM,EAAE,GAChB,CAAC,CAsCH;AAID,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;IACd,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,CAAC,CAAC;IACN,EAAE,EAAE,CAAC,CAAC;IACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC;;;;;GAqB7D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js new file mode 100644 index 0000000..f5bc33c --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js @@ -0,0 +1,225 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { validateField, nLength } from './modular.js'; +import { validateObject, bitLen } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// 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 function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.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. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + 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. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // 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. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // 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 }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // 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. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with 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 field 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 private keys / bigints) + */ +export function pippenger(c, field, 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 + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.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 = c.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; +} +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 }, + }); +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js.map new file mode 100644 index 0000000..e06c4f0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,OAAO,EAAU,aAAa,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpD,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,mFAAmF;AACnF,gDAAgD;AAChD,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAc,CAAC;AACnD,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAe,CAAC,CAAC,iEAAiE;AAEtH,6DAA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MAAM,UAAU,aAAa,CAAQ,KAAyB;IAC5D,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACxB,cAAc,CACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts new file mode 100644 index 0000000..469275d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts @@ -0,0 +1,101 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { AffinePoint, BasicCurve, Group, GroupConstructor } from './curve.js'; +import { FHash, Hex } from './utils.js'; +export type CurveType = BasicCurve & { + a: bigint; + d: bigint; + hash: FHash; + randomBytes: (bytesLength?: number) => Uint8Array; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + prehash?: FHash; + mapToCurve?: (scalar: bigint[]) => AffinePoint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly d: bigint; + readonly hash: FHash; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + readonly adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + readonly domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + readonly uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + readonly prehash?: FHash; + readonly mapToCurve?: (scalar: bigint[]) => AffinePoint; + readonly p: bigint; +}>; +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; + msm(points: ExtPointType[], scalars: bigint[]): ExtPointType; +} +/** + * Edwards Curve interface. + * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`. + */ +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { + context?: Hex; + }) => Uint8Array; + verify: (sig: Hex, message: Hex, publicKey: Hex, options?: { + context?: Hex; + zip215: boolean; + }) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +export declare function twistedEdwards(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts.map new file mode 100644 index 0000000..eecae85 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EACL,WAAW,EACX,UAAU,EACV,KAAK,EACL,gBAAgB,EAIjB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAe,KAAK,EAAE,GAAG,EAAmB,MAAM,YAAY,CAAC;AAOtE,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG;IAC3C,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,KAAK,CAAC;IACZ,WAAW,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;IAClD,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxE,OAAO,CAAC,EAAE,KAAK,CAAC;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AAU,CAAC;YACjB,MAAM,EAAE,UAAU,CAAC;YACnB,MAAM,EAAE,MAAM,CAAC;YACf,KAAK,EAAE,YAAY,CAAC;YACpB,UAAU,EAAE,UAAU,CAAC;SACxB,CAAC;KACH,CAAC;CACH,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAua3D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js new file mode 100644 index 0000000..13c943e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js @@ -0,0 +1,434 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { validateBasic, wNAF, pippenger, } from './curve.js'; +import { mod, Field } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, memoized, abool } from './utils.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +export function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + ut.aInRange('coordinate ' + title, n, _0n, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[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 private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + ut.aInRange('pointHex.y', y, _0n, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js.map new file mode 100644 index 0000000..c65bf40 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,OAAO,EAKL,aAAa,EACb,IAAI,EACJ,SAAS,GACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,WAAW,EAAc,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtE,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,KAAK,EACL;QACE,IAAI,EAAE,UAAU;QAChB,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,WAAW,EAAE,UAAU;KACxB,EACD;QACE,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,UAAU;QACnB,UAAU,EAAE,UAAU;KACvB,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAA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WAAW,CAAC,EAAE,CAAC,KAAK,CAAC;QAEzD;;;;;WAKG;QACH,UAAU,CAAC,UAAU,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI;YAC3C,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YACjC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..03f910b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts @@ -0,0 +1,58 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { AffinePoint, Group, GroupConstructor } from './curve.js'; +import { IField } from './modular.js'; +import type { CHash } from './utils.js'; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; +export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array; +export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * 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 declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +export declare function isogenyMap>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => { + x: T; + y: T; +}; +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +export type htfBasicOpts = { + DST: UnicodeOrBytes; +}; +export declare function createHasher(Point: H2CPointConstructor, mapToCurve: MapToCurve, def: Opts & { + encodeDST?: UnicodeOrBytes; +}): { + hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + mapToCurve(scalars: bigint[]): H2CPoint; +}; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..c6805c6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,MAAM,EAAO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AAQ,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;IACtC,aAAa,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC7B,cAAc,IAAI,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,mBAAmB,CAAC,CAAC,CAAE,SAAQ,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC3E,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;CAC7C;AAED,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;AAIjE,MAAM,MAAM,YAAY,GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAAC;AAEnD,wBAAgB,YAAY,CAAC,CAAC,EAC5B,KAAK,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC7B,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,EACzB,GAAG,EAAE,IAAI,GAAG;IAAE,SAAS,CAAC,EAAE,cAAc,CAAA;CAAE;qBAMvB,UAAU,YAAY,YAAY;uBAWhC,UAAU,YAAY,YAAY;wBAOjC,MAAM,EAAE;EAU/B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js new file mode 100644 index 0000000..7f6e443 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js @@ -0,0 +1,175 @@ +import { mod } from './modular.js'; +import { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.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(`bad I2OSP call: value=${value} length=${length}`); + } + 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'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +export function expand_message_xmd(msg, DST, lenInBytes, H) { + abytes(msg); + abytes(DST); + anum(lenInBytes); + // 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. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +export function expand_message_xof(msg, DST, lenInBytes, k, H) { + abytes(msg); + abytes(DST); + anum(lenInBytes); + // 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 + * 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, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + abytes(msg); + anum(count); + const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST; + 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 [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +export function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error('mapToCurve: expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') + throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); + const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..b902159 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map @@ -0,0 +1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AC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAChE,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts new file mode 100644 index 0000000..c7ccfad --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts @@ -0,0 +1,127 @@ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * 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 declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +export declare function invert(number: bigint, modulo: bigint): bigint; +/** + * 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 + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export declare function tonelliShanks(P: bigint): (Fp: IField, n: T) => T; +export declare function FpSqrt(P: bigint): (Fp: IField, n: T) => T; +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + isOdd?(num: T): boolean; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + cmov(a: T, b: T, c: boolean): T; +} +export declare function validateField(field: IField): IField; +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +export declare function FpPow(f: IField, num: T, power: bigint): T; +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export declare function FpInvertBatch(f: IField, nums: T[]): T[]; +export declare function FpDiv(f: IField, lhs: T, rhs: T | bigint): T; +export declare function FpLegendre(order: bigint): (f: IField, x: T) => T; +export declare function FpIsSquare(f: IField): (x: T) => boolean; +export declare function nLength(n: bigint, nBitLength?: number): { + nBitLength: number; + nByteLength: number; +}; +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * 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 doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial>): Readonly; +export declare function FpSqrtOdd(Fp: IField, elm: T): T; +export declare function FpSqrtEven(Fp: IField, elm: T): T; +/** + * "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 declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint; +/** + * 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 declare function getFieldBytesLength(fieldOrder: bigint): number; +/** + * 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 declare function getMinHashLength(fieldOrder: bigint): number; +/** + * "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 declare function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE?: boolean): Uint8Array; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts.map new file mode 100644 index 0000000..2d3395d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../../src/abstract/modular.ts"],"names":[],"mappings":"AAmBA,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAGhD;AACD;;;;;GAKG;AAEH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GA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M,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIlD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,UAAQ,GACX,MAAM,CAQR;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAI9D;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,UAAQ,GAAG,UAAU,CAW5F"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js new file mode 100644 index 0000000..2554a61 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js @@ -0,0 +1,426 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = 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 + */ +// TODO: use field version && remove +export function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +// 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 +export function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // 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); +} +/** + * 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 + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export function tonelliShanks(P) { + // Legendre constant: 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) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +export function FpSqrt(P) { + // NOTE: 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). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + 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)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(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 + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 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.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: 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: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// 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(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +export function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +export function FpLegendre(order) { + // (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) + const legendreConst = (order - _1n) / _2n; // Integer arithmetic + return (f, x) => f.pow(x, legendreConst); +} +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f) { + const legendre = FpLegendre(f.ORDER); + return (x) => { + const p = legendre(f, x); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +export function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * 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 doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + 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, + 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: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +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 ? bytesToNumberBE(key) : bytesToNumberLE(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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js.map new file mode 100644 index 0000000..ee5d124 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../../src/abstract/modular.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sDAAsD;AACtD,OAAO,EACL,OAAO,EACP,eAAe,EACf,eAAe,EACf,WAAW,EACX,eAAe,EACf,eAAe,EACf,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzC,wBAAwB;AACxB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS;IACtC,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAA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,IAAI;QACxC,MAAM,IAAI,KAAK,CAAC,YAAY,MAAM,6BAA6B,GAAG,EAAE,CAAC,CAAC;IACxE,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAC/D,+EAA+E;IAC/E,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;IACjD,OAAO,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACxF,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts new file mode 100644 index 0000000..69e2bc4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts @@ -0,0 +1,26 @@ +type Hex = string | Uint8Array; +export type CurveType = { + P: bigint; + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { + randomPrivateKey: () => Uint8Array; + }; + GuBytes: Uint8Array; +}; +export declare function montgomery(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..7cd3949 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../../src/abstract/montgomery.ts"],"names":[],"mappings":"AAYA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,CAAC,EAAE,MAAM,CAAC;IACV,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD,CAAC;AACF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAuBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAmIvD"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js new file mode 100644 index 0000000..38b0d5a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js @@ -0,0 +1,150 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js.map new file mode 100644 index 0000000..03998f4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EACL,QAAQ,EACR,eAAe,EACf,WAAW,EACX,eAAe,EAC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AY,eAAe,OAAO,QAAQ,eAAe,GAAG,EAAE,CAAC,CAAC;QAClF,OAAO,eAAe,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;IACnD,CAAC;IACD,SAAS,UAAU,CAAC,MAAW,EAAE,CAAM;QACrC,MAAM,MAAM,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,EAAE,GAAG,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7C,kCAAkC;QAClC,sCAAsC;QACtC,IAAI,EAAE,KAAK,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC1E,OAAO,iBAAiB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IACD,kFAAkF;IAClF,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts new file mode 100644 index 0000000..b2197b3 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +export declare function validateOpts(opts: PoseidonOpts): Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; +}>; +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +export declare function poseidon(opts: PoseidonOpts): { + (values: bigint[]): bigint[]; + roundConstants: bigint[][]; +}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..69eda8f --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAS,MAAM,EAAiB,MAAM,cAAc,CAAC;AAG5D,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY;;gBA0C5B,MAAM;;;QApDnB,MAAM,CAAC,MAAM,CAAC;OACf,MAAM;gBACG,MAAM;mBACH,MAAM;gBACT,MAAM;2BACK,OAAO;GAqD/B;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,cAarD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY;aAcU,MAAM,EAAE;;EAsB5D"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js new file mode 100644 index 0000000..79f69f5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js @@ -0,0 +1,108 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { FpPow, validateField } from './modular.js'; +export function validateOpts(opts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) + throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + if (roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} +export function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +export function poseidon(opts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js.map new file mode 100644 index 0000000..1ed92fb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sFAAsF;AACtF,OAAO,EAAE,KAAK,EAAU,aAAa,EAAE,MAAM,cAAc,CAAC;AAc5D,MAAM,UAAU,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACxE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAEzD,aAAa,CAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE,CAAC;QAC9D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CA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AK,OAAO,CAAC,GAAG,CAAC,CAAC;YACvF,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,4BAA4B;QAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,cAAc,CAAC;IAC7C,OAAO,YAAY,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts new file mode 100644 index 0000000..9a8afcf --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts @@ -0,0 +1,107 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import type { ProjConstructor, ProjPointType } from './weierstrass.js'; +export type BigintTuple = [bigint, bigint]; +export type Fp = bigint; +export type Fp2 = { + c0: bigint; + c1: bigint; +}; +export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +export type Fp6 = { + c0: Fp2; + c1: Fp2; + c2: Fp2; +}; +export type Fp12 = { + c0: Fp6; + c1: Fp6; +}; +export type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +export type Fp2Bls = mod.IField & { + reim: (num: Fp2) => { + re: Fp; + im: Fp; + }; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + fromBigTuple(num: [bigint, bigint]): Fp2; +}; +export type Fp12Bls = mod.IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; +}; +export declare function psiFrobenius(Fp: mod.IField, Fp2: Fp2Bls, base: Fp2): { + psi: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + G2psi: (c: ProjConstructor, P: ProjPointType) => ProjPointType; + G2psi2: (c: ProjConstructor, P: ProjPointType) => ProjPointType; + PSI_X: Fp2; + PSI_Y: Fp2; + PSI2_X: Fp2; + PSI2_Y: Fp2; +}; +export type Tower12Opts = { + ORDER: bigint; + NONRESIDUE?: Fp; + FP2_NONRESIDUE: BigintTuple; + Fp2sqrt?: (num: Fp2) => Fp2; + Fp2mulByB: (num: Fp2) => Fp2; + Fp12cyclotomicSquare: (num: Fp12) => Fp12; + Fp12cyclotomicExp: (num: Fp12, n: bigint) => Fp12; + Fp12finalExponentiate: (num: Fp12) => Fp12; +}; +export declare function tower12(opts: Tower12Opts): { + Fp: Readonly & Required, "isOdd">>>; + Fp2: mod.IField & { + NONRESIDUE: Fp2; + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + mulByNonresidue: (num: Fp2) => Fp2; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: mod.IField & { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + mul1(num: Fp6, b1: Fp2): Fp6; + mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + mulByFp2(lhs: Fp6, rhs: Fp2): Fp6; + }; + Fp4Square: (a: Fp2, b: Fp2) => { + first: Fp2; + second: Fp2; + }; + Fp12: mod.IField & { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + mulByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; + }; +}; +//# sourceMappingURL=tower.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts.map new file mode 100644 index 0000000..959807c --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.d.ts","sourceRoot":"","sources":["../../src/abstract/tower.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAEpC,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAmBvE,MAAM,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CA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,EAAE,WAAW,GAAG,MAAM,EAAE,KAAK,GAAG;cAC9C,CAAC,GAAG,EAAE,GAAG,KAAK;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE;yBAC7B,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG;gBAC1B,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG;0BACP,GAAG,SAAS,MAAM,GAAG,GAAG;;;oBA+J9B,CAAC,KAAK,EAAE,SAAS,KAAK,GAAG;yBACpB,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG;0BAChB,GAAG,SAAS,MAAM,GAAG,GAAG;kBAChC,GAAG,MAAM,GAAG,GAAG,GAAG;mBACjB,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG,GAAG;sBACxB,GAAG,OAAO,GAAG,GAAG,GAAG;;mBAoJb,GAAG,KAAK,GAAG,KAAG;QAAE,KAAK,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE;;uBAS9C,CAAC,CAAC,EAAE,YAAY,KAAK,IAAI;0BACtB,IAAI,SAAS,MAAM,GAAG,IAAI;oBAChC,IAAI,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG,IAAI;oBACtC,IAAI,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,GAAG,IAAI;sBACpC,IAAI,OAAO,GAAG,GAAG,IAAI;uBACpB,IAAI,GAAG,IAAI;+BACH,IAAI,GAAG,IAAI;+BACX,IAAI,GAAG,IAAI;4BACd,IAAI,KAAK,MAAM,GAAG,IAAI;;EAiH7C"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js new file mode 100644 index 0000000..7da5831 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js @@ -0,0 +1,494 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import { bitLen, bitMask, concatBytes, notImplemented } from './utils.js'; +/* +Towered extension fields + +Rather than implementing a massive 12th-degree extension directly, it is more efficient +to build it up from smaller extensions: a tower of extensions. + +For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, +on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + +For more info: "Pairings for beginners" by Costello, section 7.3. +*/ +// 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); +function calcFrobeniusCoefficients(Fp, nonResidue, modulus, degree, num = 1, divisor) { + const _divisor = BigInt(divisor === undefined ? degree : divisor); + const towerModulus = modulus ** BigInt(degree); + const res = []; + for (let i = 0; i < num; i++) { + const a = BigInt(i + 1); + const powers = []; + for (let j = 0, qPower = _1n; j < degree; j++) { + const power = ((a * qPower - a) / _divisor) % towerModulus; + powers.push(Fp.pow(nonResidue, power)); + qPower *= modulus; + } + res.push(powers); + } + return res; +} +// This works same at least for bls12-381, bn254 and bls12-377 +export function psiFrobenius(Fp, Fp2, base) { + // Ψ endomorphism + const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3) + const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2) + function psi(x, y) { + // This x10 faster than previous version in bls12-381 + const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X); + const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y); + return [x2, y2]; + } + // Ψ²(P) endomorphism (psi2(x) = psi(psi(x))) + const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3) + // This equals -1, which causes y to be Fp2.neg(y). + // But not sure if there are case when this is not true? + const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/3) + if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) + throw new Error('psiFrobenius: PSI2_Y!==-1'); + function psi2(x, y) { + return [Fp2.mul(x, PSI2_X), Fp2.neg(y)]; + } + // Map points + const mapAffine = (fn) => (c, P) => { + const affine = P.toAffine(); + const p = fn(affine.x, affine.y); + return c.fromAffine({ x: p[0], y: p[1] }); + }; + const G2psi = mapAffine(psi); + const G2psi2 = mapAffine(psi2); + return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y }; +} +export function tower12(opts) { + const { ORDER } = opts; + // Fp + const Fp = mod.Field(ORDER); + const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1)); + const FpLegendre = mod.FpLegendre(ORDER); + const Fpdiv2 = Fp.div(Fp.ONE, _2n); // 1/2 + // Fp2 + const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0]; + const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), + }); + const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), + }); + const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; + }; + const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; + }; + const Fp2fromBigTuple = (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }; + const FP2_ORDER = ORDER * ORDER; + const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE); + const Fp2 = { + ORDER: FP2_ORDER, + NONRESIDUE: Fp2Nonresidue, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (opts.Fp2sqrt) + return opts.Fp2sqrt(num); + // This is generic for all quadratic extensions (Fp2) + const { c0, c1 } = num; + if (Fp.is0(c1)) { + // if c0 is quadratic residue + if (Fp.eql(FpLegendre(Fp, c0), Fp.ONE)) + return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO }); + else + return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) }); + } + const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE))); + let d = Fp.mul(Fp.add(a, c0), Fpdiv2); + const legendre = FpLegendre(Fp, d); + // -1, Quadratic non residue + if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE)) + d = Fp.sub(d, a); + const a0 = Fp.sqrt(d); + const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) }); + if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) + throw new Error('Cannot find square root'); + // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num + const x1 = candidateSqrt; + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatBytes(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue), + mulByB: opts.Fp2mulByB, + fromBigTuple: Fp2fromBigTuple, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), + }; + // Fp6 + const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), + }); + const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), + }); + const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; + }; + const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; + }; + const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 6, 2, 3); + const Fp6 = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: notImplemented, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + mul1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + mul01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + }; + // Fp12 + const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 12, 1, 6)[0]; + const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), + }); + const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), + }); + const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; + }; + const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB + }; + function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; + } + const Fp12 = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: notImplemented, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: Fp6.frobeniusMap(lhs.c0, power), + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + mulByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.mulByFp2(c0, rhs), + c1: Fp6.mulByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // Sparse multiplication + mul014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.mul01(c0, o0, o1); + let t1 = Fp6.mul1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + mul034: ({ c0, c1 }, o0, o3, o4) => { + const a = Fp6.create({ + c0: Fp2.mul(c0.c0, o0), + c1: Fp2.mul(c0.c1, o0), + c2: Fp2.mul(c0.c2, o0), + }); + const b = Fp6.mul01(c1, o3, o4); + const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(b), a), + c1: Fp6.sub(e, Fp6.add(a, b)), + }; + }, + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: opts.Fp12cyclotomicSquare, + _cyclotomicExp: opts.Fp12cyclotomicExp, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: opts.Fp12finalExponentiate, + }; + return { Fp, Fp2, Fp6, Fp4Square, Fp12 }; +} +//# sourceMappingURL=tower.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js.map new file mode 100644 index 0000000..92455cb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/tower.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.js","sourceRoot":"","sources":["../../src/abstract/tower.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAG1E;;;;;;;;;;EAUE;AAEF,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAgCzE,SAAS,yBAAyB,CAChC,EAAiB,EACjB,UAAa,EACb,OAAe,EACf,MAAc,EACd,MAAc,CAAC,EACf,OAAgB;IAEhB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IAClE,MAAM,YAAY,GAAQ,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,GAAG,GAAU,EAAE,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7B,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC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at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts new file mode 100644 index 0000000..f3ce585 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts @@ -0,0 +1,111 @@ +export type Hex = Uint8Array | string; +export type PrivKey = Hex | bigint; +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { + dkLen?: number; + }): any; +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; +export declare function isBytes(a: unknown): a is Uint8Array; +export declare function abytes(item: unknown): void; +export declare function abool(title: string, value: boolean): void; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function numberToHexUnpadded(num: number | bigint): string; +export declare function hexToNumber(hex: string): bigint; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function bytesToNumberLE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array; +export declare function numberToVarBytesBE(n: number | bigint): Uint8Array; +/** + * 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. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export declare function inRange(n: bigint, min: bigint, max: bigint): boolean; +/** + * 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 declare function aInRange(title: string, n: bigint, min: bigint, max: bigint): void; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + */ +export declare function bitSet(n: bigint, pos: number, value: boolean): bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: Uint8Array) => T | undefined; +/** + * 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(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred) => T; +declare const validatorFns: { + readonly bigint: (val: any) => val is bigint; + readonly function: (val: any) => boolean; + readonly boolean: (val: any) => val is boolean; + readonly string: (val: any) => val is string; + readonly stringOrUint8Array: (val: any) => val is string | Uint8Array; + readonly isSafeInteger: (val: any) => boolean; + readonly array: (val: any) => val is any[]; + readonly field: (val: any, object: any) => any; + readonly hash: (val: any) => boolean; +}; +type Validator = keyof typeof validatorFns; +type ValMap> = { + [K in keyof T]?: Validator; +}; +export declare function validateObject>(object: T, validators: ValMap, optValidators?: ValMap): T; +/** + * throws not implemented error + */ +export declare const notImplemented: () => never; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +export declare function memoized(fn: (arg: T, ...args: O) => R): (arg: T, ...args: O) => R; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts.map new file mode 100644 index 0000000..973b2e5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,GAAG,CAAC;CACxC,CAAC;AACF,MAAM,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,KAAK,UAAU,CAAC;AAEjE,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAKnD;AAED,wBAAgB,MAAM,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAE1C;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAGzD;AAMD;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQpD;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAGhE;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAI/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AAC,SAAS,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,SAE7E,CAAC,WAAW,CAAC,KAAG,CAAC,CAO/B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js new file mode 100644 index 0000000..fdb5fd6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js @@ -0,0 +1,333 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +export function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +export function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +export function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +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); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${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(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @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); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded 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; + } + return array; +} +// 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. 'private 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 valid hex string, got "${hex}". 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} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * 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; +} +// 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; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// 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 ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +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) => (_2n << BigInt(n - 1)) - _1n; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * 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(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) + 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()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([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 = { [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 "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + 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' }); +/** + * 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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js.map new file mode 100644 index 0000000..8b8bd08 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAWtC,MAAM,UAAU,OAAO,CAAC,CAAU;IAChC,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,CAAC,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,YAAY,CAAC,CAC5E,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,IAAa;IAClC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,UAAU,KAAK,CAAC,KAAa,EAAE,KAAc;IACjD,IAAI,OAAO,KAAK,KAAK,SAAS;QAC5B,MAAM,IAAI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AM,QAAQ,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;QAClC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QACvB,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts new file mode 100644 index 0000000..394182e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts @@ -0,0 +1,258 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { AffinePoint, BasicCurve, Group, GroupConstructor } from './curve.js'; +import * as mod from './modular.js'; +import { CHash, Hex, PrivKey } from './utils.js'; +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +export type BasicWCurve = BasicCurve & { + a: T; + b: T; + allowedPrivateKeyLengths?: readonly number[]; + wrapPrivateKey?: boolean; + endo?: EndomorphismOpts; + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; +type Entropy = Hex | boolean; +export type SignOpts = { + lowS?: boolean; + extraEntropy?: Entropy; + prehash?: boolean; +}; +export type VerOpts = { + lowS?: boolean; + prehash?: boolean; +}; +/** + * ### 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 + */ +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; + msm(points: ProjPointType[], scalars: bigint[]): ProjPointType; +} +export type CurvePointsType = BasicWCurve & { + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; +declare function validatePointOpts(curve: CurvePointsType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: T; + readonly Gy: T; + readonly allowInfinityPoint?: boolean; + readonly a: T; + readonly b: T; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: EndomorphismOpts; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint) | undefined; + readonly toBytes?: ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array) | undefined; + readonly p: bigint; +}>; +export type CurvePointsRes = { + CURVE: ReturnType>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +/** + * 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 declare const DER: { + Err: { + new (m?: string): { + name: string; + message: string; + stack?: string; + }; + }; + _tlv: { + encode: (tag: number, data: string) => string; + decode(tag: number, data: Uint8Array): { + v: Uint8Array; + l: Uint8Array; + }; + }; + _int: { + encode(num: bigint): string; + decode(data: Uint8Array): bigint; + }; + toSig(hex: string | Uint8Array): { + r: bigint; + s: bigint; + }; + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +export declare function weierstrassPoints(opts: CurvePointsType): CurvePointsRes; +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { + r: bigint; + s: bigint; +}; +export type PubKey = Hex | ProjPointType; +export type CurveType = BasicWCurve & { + hash: CHash; + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: EndomorphismOpts; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: HmacFnSync; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; +}>; +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +export declare function weierstrass(curveDef: CurveType): CurveFn; +/** + * 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 declare function SWUFpSqrtRatio(Fp: mod.IField, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +export declare function mapToCurveSimpleSWU(Fp: mod.IField, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..a7fd017 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EACL,WAAW,EACX,UAAU,EACV,KAAK,EACL,gBAAgB,EAIjB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAEpC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAgC,MAAM,YAAY,CAAC;AAE/E,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,CAAC;AAC7E,KAAK,gBAAgB,GAAG;IACtB,IAAI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AM,CAAC,CAAC,CAAC,EACjB,IAAI,EAAE;IACJ,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,OASU,CAAC,KAAG;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC,EAAE,CAAC,CAAA;CAAE,CA8B9B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js new file mode 100644 index 0000000..681aefd --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js @@ -0,0 +1,1138 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import { validateBasic, wNAF, pippenger, } from './curve.js'; +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, memoized, abool } from './utils.js'; +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * 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: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // 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 = ut.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 ? ut.numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${ut.numberToHexUnpadded(tag)}${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 = ut.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 assertion'); + 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 b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + ut.abytes(data); + 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 seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + 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 weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = mod.Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return ut.inRange(num, _1n, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (ut.isBytes(key)) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, N); // disabled by default, enabled for BLS + ut.aInRange('private key', num, _1n, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // 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 { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, 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 ax = Fp.mul(x, iz); + const ay = 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: ax, y: ay }; + }); + // 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 wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * 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 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + 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'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * 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. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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.px, Fp.neg(this.py), this.pz); + } + // 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 { px: X1, py: Y1, pz: 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) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * 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 private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + ut.aInRange('scalar', sc, _0n, CURVE.n); + const I = Point.ZERO; + if (sc === _0n) + return I; + if (sc === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * 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, n: N } = CURVE; + ut.aInRange('scalar', scalar, _1n, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // 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) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +export function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!ut.inRange(x, _1n, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N] + ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = ut.isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // 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 = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = ut.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. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // 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 + const s = modN(ik * modN(m + r * d)); // Not using blinding here + 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 = normalizeS(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 }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. 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, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || ut.isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * 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) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // 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, opts.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, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.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, opts.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, opts.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) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js.map b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js.map new file mode 100644 index 0000000..fe2f123 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,OAAO,EAKL,aAAa,EACb,IAAI,EACJ,SAAS,GACV,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAuB,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AA4B/E,SAAS,kBAAkB,CAAC,IAAwB;IAClD,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS;QAAE,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACtD,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;QAAE,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;AACjE,CAAC;AA4DD,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,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,mBAAmB;QACzC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,wCAAwC;QACtE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,uCAAuC;QACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts new file mode 100644 index 0000000..fd20783 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts @@ -0,0 +1,3 @@ +import { CurveFn } from './abstract/bls.js'; +export declare const bls12_381: CurveFn; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts.map new file mode 100644 index 0000000..475c0ed --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.d.ts","sourceRoot":"","sources":["../src/bls12-381.ts"],"names":[],"mappings":"AAGA,OAAO,EAAO,OAAO,EAAE,MAAM,mBAAmB,CAAC;AA2ajD,eAAO,MAAM,SAAS,EAAE,OAqUtB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js new file mode 100644 index 0000000..1919c78 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js @@ -0,0 +1,702 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { bitGet, bitLen, bytesToHex, bytesToNumberBE, concatBytes as concatB, ensureBytes, numberToBytesBE, } from './abstract/utils.js'; +// Types +import { isogenyMap } from './abstract/hash-to-curve.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { tower12, psiFrobenius } from './abstract/tower.js'; +/* +bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to: +- Construct zk-SNARKs at the 120-bit security +- Efficiently verify N aggregate signatures with 1 pairing and N ec additions: + the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr + +### Summary +1. BLS Relies on Bilinear Pairing (expensive) +2. Private Keys: 32 bytes +3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. + - The signature is a point on the G2 subgroup, which is defined over a finite field + with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +5. The 12 stands for the Embedding degree. + +### Formulas +- `P = pk x G` - public keys +- `S = pk x H(m)` - signing +- `e(P, H(m)) == e(G, S)` - verification using pairings +- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation + +### Compatibility and notes +1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC + Filecoin uses little endian byte arrays for private keys - make sure to reverse byte order. +2. Some projects use G2 for public keys and G1 for signatures. It's called "short signature" +3. Curve security level is about 120 bits as per Barbulescu-Duquesne 2017 + https://hal.science/hal-01534101/file/main.pdf +4. Compatible with specs: +[cfrg-pairing-friendly-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +[cfrg-bls-signature-05](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05), +[RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). +*/ +// 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); +/* +Embedding degree (k): 12 +Seed (X): -15132376222941642752 +Fr: (x⁴-x²+1) +Fp: ((x-1)² ⋅ r(x)/3+x) +(E/Fp): Y²=X³+4 +(Eₜ/Fp²): Y² = X³+4(u+1) (M-type twist) +Ate loop size: X + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-1-u +- Fp¹²[w] = Fp⁶/w²-v + + +TODO: BLS & BN Fp/Fr can be constructed from seed. +*/ +// The BLS parameter x (seed) for BLS12-381. NOTE: it is negative! +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); +// CURVE FIELDS +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = tower12({ + // Order of Fp + ORDER: BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'), + // Finite extension field over irreducible polynominal. + // Fp(u) / (u² - β) where β = -1 + FP2_NONRESIDUE: [_1n, _1n], + Fp2mulByB: ({ c0, c1 }) => { + const t0 = Fp.mul(c0, _4n); // 4 * c0 + const t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + // Fp12 + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = isogenyMap(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const { G2psi, G2psi2 } = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); // 1/(u+1) +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +// Compressed point of infinity +const COMPRESSED_ZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true }); // set compressed & point-at-infinity bits +function parseMask(bytes) { + // Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo. + bytes = bytes.slice(); + const mask = bytes[0] & 224; + const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000) + const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000) + const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000) + bytes[0] &= 31; // clear mask (zero first 3 bits) + return { compressed, infinity, sort, value: bytes }; +} +function setMask(bytes, mask) { + if (bytes[0] & 224) + throw new Error('setMask: non-empty mask'); + if (mask.compressed) + bytes[0] |= 128; + if (mask.infinity) + bytes[0] |= 64; + if (mask.sort) + bytes[0] |= 32; + return bytes; +} +function signatureG1ToRawBytes(point) { + point.assertValidity(); + const isZero = point.equals(bls12_381.G1.ProjectivePoint.ZERO); + const { x, y } = point.toAffine(); + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort }); +} +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const sort = Boolean((tmp / Fp.ORDER) & _1n); + const z2 = x0; + return concatB(setMask(numberToBytesBE(x1, len), { sort, compressed: true }), numberToBytesBE(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381 = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P + const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(BLS_X).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if (value.length === 48 && compressed) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(value); + // Zero + const x = Fp.create(compressedValue & Fp.MASK); + if (infinity) { + if (x !== _0n) + throw new Error('G1: non-empty compressed point at infinity'); + return { x: _0n, y: _0n }; + } + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + if ((y * _2n) / P !== BigInt(sort)) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (value.length === 96 && !compressed) { + // Check if the infinity flag is set + const x = bytesToNumberBE(value.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(value.subarray(Fp.BYTES)); + if (infinity) { + if (x !== _0n || y !== _0n) + throw new Error('G1: non-empty point at infinity'); + return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + } + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort }); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + ShortSignature: { + fromHex(hex) { + const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex, 48)); + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(value); + // Zero + if (infinity) + return bls12_381.G1.ProjectivePoint.ZERO; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = BigInt(sort); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + const point = bls12_381.G1.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG1ToRawBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG1ToRawBytes(point)); + }, + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = BLS_X; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if ((!compressed && !infinity && sort) || // 00100000 + (!compressed && infinity && sort) || // 01100000 + (sort && infinity && compressed) // 11100000 + ) { + throw new Error('Invalid encoding flag: ' + (bytes[0] & 224)); + } + const L = Fp.BYTES; + const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + if (value.length === 96 && compressed) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + if (infinity) { + // check that all bytes are 0 + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(value, 0, L); + const x_0 = slc(value, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = sort && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (value.length === 192 && !compressed) { + if (infinity) { + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid uncompressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(value, 0, L); + const x0 = slc(value, L, 2 * L); + const y1 = slc(value, 2 * L, 3 * L); + const y0 = slc(value, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + return concatB(setMask(numberToBytesBE(x.c1, len), { compressed: true, sort: flag }), numberToBytesBE(x.c0, len)); + } + else { + if (isZero) + return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex)); + const P = Fp.ORDER; + const half = value.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(value.slice(0, half)); + const z2 = bytesToNumberBE(value.slice(half)); + // Indicates the infinity point + if (infinity) + return bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = BigInt(sort); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + xNegative: true, + twistType: 'multiplicative', + }, + htfDefaults, + hash: sha256, + randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js.map b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js.map new file mode 100644 index 0000000..3cc8b3b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["../src/bls12-381.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAW,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EACL,MAAM,EACN,MAAM,EACN,UAAU,EACV,eAAe,EACf,WAAW,IAAI,OAAO,EACtB,WAAW,EAEX,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAC7B,QAAQ;AACR,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO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,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts b/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts new file mode 100644 index 0000000..4f7252a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts @@ -0,0 +1,13 @@ +import { CurveFn } from './abstract/bls.js'; +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings. + */ +export declare const bn254: CurveFn; +/** + * bn254 weierstrass curve with ECDSA. + * This is very rare and probably not used anywhere. + * Instead, you should use G1 / G2, defined above. + */ +export declare const bn254_weierstrass: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts.map new file mode 100644 index 0000000..7c62569 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["../src/bn254.ts"],"names":[],"mappings":"AAKA,OAAO,EAAO,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAiJjD;;;GAGG;AACH,eAAO,MAAM,KAAK,EAAE,OAkElB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,6CAS5B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bn254.js b/src/libMPC/node_modules/@noble/curves/esm/bn254.js new file mode 100644 index 0000000..0d95056 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bn254.js @@ -0,0 +1,220 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { getHash } from './_shortw_utils.js'; +import { weierstrass } from './abstract/weierstrass.js'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls } from './abstract/bls.js'; +import { Field } from './abstract/modular.js'; +import { bitGet, bitLen, notImplemented } from './abstract/utils.js'; +import { tower12, psiFrobenius } from './abstract/tower.js'; +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _6n = BigInt(6); +/* +bn254, previously known as alt_bn_128, when it had 128-bit security. +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/execution-specs/blob/master/src/ethereum/crypto/alt_bn128.py +- Points are encoded differently in different implementations +*/ +/* +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v +*/ +const BN_X = BigInt('4965661367192848881'); +const BN_X_LEN = bitLen(BN_X); +const SIX_X_SQUARED = _6n * BN_X ** _2n; +// Finite field over r. It's for convenience and is not used in the code below. +const Fr = Field(BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617')); +// Fp2.div(Fp2.mul(Fp2.ONE, _3n), Fp2.NONRESIDUE) +const Fp2B = { + c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'), + c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'), +}; +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = tower12({ + ORDER: BigInt('21888242871839275222246405745257275088696311157297823662689037894645226208583'), + FP2_NONRESIDUE: [BigInt(9), _1n], + Fp2mulByB: (num) => Fp2.mul(num, Fp2B), + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BN_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const powMinusX = (num) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X)); + const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num)); + const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0); + const y1 = Fp12._cyclotomicSquare(powMinusX(r)); + const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1); + const y4 = powMinusX(y2); + const y6 = powMinusX(Fp12._cyclotomicSquare(y4)); + const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2)); + const y9 = Fp12.mul(y8, y1); + return Fp12.mul(Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), Fp12.mul(Fp12.frobeniusMap(y8, 2), Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r)))); + }, +}); +// END OF CURVE FIELDS +const { G2psi, psi } = psiFrobenius(Fp, Fp2, Fp2.NONRESIDUE); +/* +No hashToCurve for now (and signatures): + +- RFC 9380 doesn't mention bn254 and doesn't provide test vectors +- Overall seems like nobody is using BLS signatures on top of bn254 +- Seems like it can utilize SVDW, which is not implemented yet +*/ +const htfDefaults = Object.freeze({ + // DST: a domain separation tag defined in section 2.2.5 + DST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + p: Fp.ORDER, + m: 2, + k: 128, + expand: 'xmd', + hash: sha256, +}); +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings. + */ +export const bn254 = bls({ + // Fields + fields: { Fp, Fp2, Fp6, Fp12, Fr }, + G1: { + Fp, + h: BigInt(1), + Gx: BigInt(1), + Gy: BigInt(2), + a: Fp.ZERO, + b: _3n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: notImplemented, + fromBytes: notImplemented, + toBytes: notImplemented, + ShortSignature: { + fromHex: notImplemented, + toRawBytes: notImplemented, + toHex: notImplemented, + }, + }, + G2: { + Fp: Fp2, + // cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1 + h: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + Gx: Fp2.fromBigTuple([ + BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'), + BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'), + BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'), + ]), + a: Fp2.ZERO, + b: Fp2B, + hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P + mapToCurve: notImplemented, + fromBytes: notImplemented, + toBytes: notImplemented, + Signature: { + fromHex: notImplemented, + toRawBytes: notImplemented, + toHex: notImplemented, + }, + }, + params: { + ateLoopSize: BN_X * _6n + _2n, + r: Fr.ORDER, + xNegative: false, + twistType: 'divisive', + }, + htfDefaults, + hash: sha256, + randomBytes, + postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => { + const q = psi(Qx, Qy); + ({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1])); + const q2 = psi(q[0], q[1]); + pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1])); + }, +}); +/** + * bn254 weierstrass curve with ECDSA. + * This is very rare and probably not used anywhere. + * Instead, you should use G1 / G2, defined above. + */ +export const bn254_weierstrass = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp, + n: BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/bn254.js.map b/src/libMPC/node_modules/@noble/curves/esm/bn254.js.map new file mode 100644 index 0000000..6aa3a06 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["../src/bn254.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAW,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAG5D,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACxD,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEtB;;;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F,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,WAAW,CAAC;IAC3C,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE;IACF,CAAC,EAAE,MAAM,CAAC,+EAA+E,CAAC;IAC1F,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts b/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts new file mode 100644 index 0000000..6172a96 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts @@ -0,0 +1,81 @@ +import { AffinePoint, Group } from './abstract/curve.js'; +import { CurveFn, ExtPointType } from './abstract/edwards.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Hex } from './abstract/utils.js'; +export declare const ED25519_TORSION_SUBGROUP: string[]; +/** + * ed25519 curve with EdDSA signatures. + */ +export declare const ed25519: CurveFn; +export declare const ed25519ctx: CurveFn; +export declare const ed25519ph: CurveFn; +export declare const x25519: import("./abstract/montgomery.js").CurveFn; +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export declare function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class RistPoint implements Group { + private readonly ep; + static BASE: RistPoint; + static ZERO: RistPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): RistPoint; + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint; + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: RistPoint): boolean; + add(other: RistPoint): RistPoint; + subtract(other: RistPoint): RistPoint; + multiply(scalar: bigint): RistPoint; + multiplyUnsafe(scalar: bigint): RistPoint; + double(): RistPoint; + negate(): RistPoint; +} +export declare const RistrettoPoint: typeof RistPoint; +export declare const hashToRistretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export declare const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts.map new file mode 100644 index 0000000..2c85acf --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed25519.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAoC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG7F,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AA0E7B,eAAO,MAAM,wBAAwB,UASpC,CAAC;AA8BF;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,OAAmE,CAAC;AAY1F,eAAO,MAAM,UAAU,SAIhB,CAAC;AACR,eAAO,MAAM,SAAS,SAMhB,CAAC;AAEP,eAAO,MAAM,MAAM,4CAeZ,CAAC;AAER;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAIlE;AACD,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AAE1D;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,UAAU,GAAG,UAAU,CAG3E;AA0FD,eAAO,MAAM,WAAW,qGAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,qGAA8C,CAAC;AAiCzE,KAAK,aAAa,GAAG,YAAY,CAAC;AA0BlC;;;;;;GAMG;AACH,cAAM,SAAU,YAAW,KAAK,CAAC,SAAS,CAAC;IAK7B,OAAO,CAAC,QAAQ,CAAC,EAAE;IAJ/B,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC;IACvB,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC;gBAGM,EAAE,EAAE,aAAa;IAE9C,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC;IAIzC;;;;;;OAMG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,SAAS;IASvC;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,SAAS;IA2BnC;;;OAGG;IACH,UAAU,IAAI,UAAU;IA4BxB,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAKlB,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO;IAWjC,GAAG,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS;IAKhC,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS;IAKrC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAInC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAIzC,MAAM,IAAI,SAAS;IAInB,MAAM,IAAI,SAAS;CAGpB;AACD,eAAO,MAAM,cAAc,kBAIvB,CAAC;AAGL,eAAO,MAAM,kBAAkB,QAAS,UAAU,WAAW,YAAY,cAMxE,CAAC;AACF,eAAO,MAAM,oBAAoB,QAPO,UAAU,WAAW,YAAY,cAOnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed25519.js b/src/libMPC/node_modules/@noble/curves/esm/ed25519.js new file mode 100644 index 0000000..f3f40ca --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed25519.js @@ -0,0 +1,443 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _5n = BigInt(5), _8n = BigInt(8); +function ed25519_pow_2_252_3(x) { + // prettier-ignore + const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) + x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))(); +const ed25519Defaults = /* @__PURE__ */ (() => ({ + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: _8n, + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}))(); +/** + * ed25519 curve with EdDSA signatures. + */ +export const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))(); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +export const ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, +}))(); +export const ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, { + domain: ed25519_domain, + prehash: sha512, +})))(); +export const x25519 = /* @__PURE__ */ (() => montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, _3n, P) * b2, P); + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1 +const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1) +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic + const ELL2_J = BigInt(486662); + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } + double() { + return new RistPoint(this.ep.double()); + } + negate() { + return new RistPoint(this.ep.negate()); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +export const hashToRistretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_ristretto255 = hashToRistretto255; // legacy +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed25519.js.map b/src/libMPC/node_modules/@noble/curves/esm/ed25519.js.map new file mode 100644 index 0000000..55623ee --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAE5E,OAAO,EAAyB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAgB,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EACL,UAAU,EACV,eAAe,EACf,WAAW,EACX,UAAU,EAEV,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAE7B;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,eA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/@noble/curves/esm/ed448.d.ts new file mode 100644 index 0000000..2c34043 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts @@ -0,0 +1,67 @@ +import { AffinePoint, Group } from './abstract/curve.js'; +import { ExtPointType } from './abstract/edwards.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Hex } from './abstract/utils.js'; +export declare const ed448: import("./abstract/edwards.js").CurveFn; +export declare const ed448ph: import("./abstract/edwards.js").CurveFn; +export declare const x448: import("./abstract/montgomery.js").CurveFn; +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class DcfPoint implements Group { + private readonly ep; + static BASE: DcfPoint; + static ZERO: DcfPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): DcfPoint; + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex: Hex): DcfPoint; + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: Hex): DcfPoint; + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: DcfPoint): boolean; + add(other: DcfPoint): DcfPoint; + subtract(other: DcfPoint): DcfPoint; + multiply(scalar: bigint): DcfPoint; + multiplyUnsafe(scalar: bigint): DcfPoint; + double(): DcfPoint; + negate(): DcfPoint; +} +export declare const DecafPoint: typeof DcfPoint; +export declare const hashToDecaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export declare const hash_to_decaf448: (msg: Uint8Array, options: htfBasicOpts) => DcfPoint; +export {}; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts.map new file mode 100644 index 0000000..36885c5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAoC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG7F,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAsH7B,eAAO,MAAM,KAAK,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C;AAGL,eAAO,MAAM,cAAc,QAAS,UAAU,WAAW,YAAY,aAMpE,CAAC;AACF,eAAO,MAAM,gBAAgB,QAPO,UAAU,WAAW,YAAY,aAOvB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed448.js b/src/libMPC/node_modules/@noble/curves/esm/ed448.js new file mode 100644 index 0000000..621aa56 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed448.js @@ -0,0 +1,401 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { createHasher, expand_message_xof } from './abstract/hash-to-curve.js'; +import { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + 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 b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +export const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +export const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertDcfPoint(other) { + if (!(other instanceof DcfPoint)) + throw new Error('DecafPoint expected'); +} +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B); +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0) { + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + let v_prime = v; // 5 + if (!was_square) + v_prime = mod(r0 * v); + let sgn = _1n; // 6 + if (!was_square) + sgn = mod(-_1n); + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) + s_abs = mod(-s); + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint { + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex) { + hex = ensureBytes('decafHex', hex, 56); + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) + u3 = mod(-u3); + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + if (!isValid) + throw new Error(emsg); + return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes() { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) + ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 56); + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other) { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + add(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new DcfPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } + double() { + return new DcfPoint(this.ep.double()); + } + negate() { + return new DcfPoint(this.ep.negate()); + } +} +export const DecafPoint = /* @__PURE__ */ (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) + DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) + DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +export const hashToDecaf448 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_decaf448 = hashToDecaf448; // legacy +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/ed448.js.map b/src/libMPC/node_modules/@noble/curves/esm/ed448.js.map new file mode 100644 index 0000000..59b9648 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE7F,OAAO,EAAgB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAgB,MAAM,6BAA6B,CAAC;AAC7F,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EACL,UAAU,EACV,eAAe,EACf,WAAW,EACX,UAAU,EAEV,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAE7B;;;;;;GAMG;AAEH,MAAM,YAAY,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AAC5E,MAAM,WAAW,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1E,MAAM,MAAM,GAAG,MAAM,CACnB,yIAAyI,CAC1I,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,C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AC,CAAC;IAC3E,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC,EAAE,CAAC;AAEL,yEAAyE;AACzE,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IACvE,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IACvE,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AACF,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC,CAAC,SAAS"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/index.d.ts b/src/libMPC/node_modules/@noble/curves/esm/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/index.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/index.d.ts.map new file mode 100644 index 0000000..535b86d --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/index.js b/src/libMPC/node_modules/@noble/curves/esm/index.js new file mode 100644 index 0000000..d02dc7a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/index.js @@ -0,0 +1,3 @@ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/index.js.map b/src/libMPC/node_modules/@noble/curves/esm/index.js.map new file mode 100644 index 0000000..d17f53a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts b/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts new file mode 100644 index 0000000..7d2c398 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts @@ -0,0 +1,9 @@ +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export declare const jubjub: import("./abstract/edwards.js").CurveFn; +export declare function groupHash(tag: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +export declare function findGroupHash(m: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +//# sourceMappingURL=jubjub.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts.map new file mode 100644 index 0000000..cd67241 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/jubjub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["../src/jubjub.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AAEH,eAAO,MAAM,MAAM,yCAgBR,CAAC;AAOZ,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAUrE;AAKD,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAWvE"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/jubjub.js b/src/libMPC/node_modules/@noble/curves/esm/jubjub.js new file mode 100644 index 0000000..b2a1e05 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/jubjub.js @@ -0,0 +1,60 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { blake2s } from '@noble/hashes/blake2s'; +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { Field } from './abstract/modular.js'; +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export const jubjub = /* @__PURE__ */ twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +}); +const GH_FIRST_BLOCK = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag, personalization) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +// No secret data is leaked here at all. +// It operates over public data: +// const G_SPEND = jubjub.findGroupHash(new Uint8Array(), utf8ToBytes('Item_G_')); +export function findGroupHash(m, personalization) { + const tag = concatBytes(m, new Uint8Array([0])); + const hashes = []; + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + hashes.push(groupHash(tag, personalization)); + } + catch (e) { } + } + if (!hashes.length) + throw new Error('findGroupHash tag overflow'); + return hashes[0]; +} +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/jubjub.js.map b/src/libMPC/node_modules/@noble/curves/esm/jubjub.js.map new file mode 100644 index 0000000..2cca8dc --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["../src/jubjub.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C;;;;GAIG;AAEH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,cAAc,CAAC;IACnD,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,C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AC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC;YACH,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC,CAAC;QAC/C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;IAChB,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts b/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts new file mode 100644 index 0000000..5c02dff --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts @@ -0,0 +1,105 @@ +export declare const p256: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp256r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p256.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts.map new file mode 100644 index 0000000..3004842 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.d.ts","sourceRoot":"","sources":["../src/p256.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiCi5xB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtBlk0B,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqB44xB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArBxj0B,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p256.js b/src/libMPC/node_modules/@noble/curves/esm/p256.js new file mode 100644 index 0000000..b36f749 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p256.js @@ -0,0 +1,42 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +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'; +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); +export const secp256r1 = p256; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p256.js.map b/src/libMPC/node_modules/@noble/curves/esm/p256.js.map new file mode 100644 index 0000000..45c5e09 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["../src/p256.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE7F,kBAAkB;AAClB,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC;IAC9B,CAAC,EAAE,OAAO,EAAE,wBAAwB;IACpC,CAAC,EAAE,OAAO;IACV,EAAE,EAAE,yDAAyD;IAC7D,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,MAAM,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,mBAAmB,CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts b/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts new file mode 100644 index 0000000..aa88088 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts @@ -0,0 +1,105 @@ +export declare const p384: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp384r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p384.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts.map new file mode 100644 index 0000000..82b1827 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p384.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiCqpxB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtBt0zB,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqBgpxB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArB5zzB,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p384.js b/src/libMPC/node_modules/@noble/curves/esm/p384.js new file mode 100644 index 0000000..7d7cbe9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p384.js @@ -0,0 +1,46 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha384 } from '@noble/hashes/sha512'; +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'; +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); +export const secp384r1 = p384; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p384.js.map b/src/libMPC/node_modules/@noble/curves/esm/p384.js.map new file mode 100644 index 0000000..289137f --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,kBAAkB;AAClB,MAAM,OAAO,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AAE7H,kBAAkB;AAClB,MAAM,CAAC,MAAM,IA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aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts b/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts new file mode 100644 index 0000000..26ac25b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts @@ -0,0 +1,105 @@ +export declare const p521: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp521r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p521.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts.map new file mode 100644 index 0000000..de8fad2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p521.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.d.ts","sourceRoot":"","sources":["../src/p521.ts"],"names":[],"mappings":"AAmCA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiC4wwB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtB77yB,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqBuwwB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArBn7yB,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p521.js b/src/libMPC/node_modules/@noble/curves/esm/p521.js new file mode 100644 index 0000000..b047ccc --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p521.js @@ -0,0 +1,53 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +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'; +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); +export const secp521r1 = p521; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/p521.js.map b/src/libMPC/node_modules/@noble/curves/esm/p521.js.map new file mode 100644 index 0000000..74a5599 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/p521.js.map @@ -0,0 +1 @@ +{"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B,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,mDAAmD;CACrF,EAAE,MAAM,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,mBAAmB,CAAC,EAAE,EAAE;IACtB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/package.json b/src/libMPC/node_modules/@noble/curves/esm/package.json new file mode 100644 index 0000000..7f1fc33 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/package.json @@ -0,0 +1,4 @@ +{ + "type": "module", + "sideEffects": false +} diff --git a/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts b/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts new file mode 100644 index 0000000..9e1f4ed --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts @@ -0,0 +1,5 @@ +export declare const p: bigint; +export declare const q: bigint; +export declare const pallas: import("./abstract/weierstrass.js").CurveFn; +export declare const vesta: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=pasta.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts.map new file mode 100644 index 0000000..6cd1333 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/pasta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.d.ts","sourceRoot":"","sources":["../src/pasta.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,CAAC,QAA+E,CAAC;AAC9F,eAAO,MAAM,CAAC,QAA+E,CAAC;AAG9F,eAAO,MAAM,MAAM,6CASjB,CAAC;AAEH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/pasta.js b/src/libMPC/node_modules/@noble/curves/esm/pasta.js new file mode 100644 index 0000000..44a7178 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/pasta.js @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { getHash } from './_shortw_utils.js'; +import { Field, mod } from './abstract/modular.js'; +import { weierstrass } from './abstract/weierstrass.js'; +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: Field(p), + n: q, + Gx: mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: Field(q), + n: p, + Gx: mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/pasta.js.map b/src/libMPC/node_modules/@noble/curves/esm/pasta.js.map new file mode 100644 index 0000000..dd878ed --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["../src/pasta.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAExD,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAC9F,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,WAAW,CAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACtB,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AACzC,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACtB,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts new file mode 100644 index 0000000..1458b4e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts @@ -0,0 +1,99 @@ +import { mod } from './abstract/modular.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, numberToBytesBE } from './abstract/utils.js'; +import { ProjPointType as PointType } from './abstract/weierstrass.js'; +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +export declare const secp256k1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => PointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: Hex | { + r: bigint; + s: bigint; + }, msgHash: Hex, publicKey: Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: PointType) => PointType; + }; +}>; +declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +declare function schnorrGetPublicKey(privateKey: Hex): Uint8Array; +/** + * 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. + */ +declare function schnorrSign(message: Hex, privateKey: PrivKey, auxRand?: Hex): Uint8Array; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean; +/** + * Schnorr signatures over secp256k1. + */ +export declare const schnorr: { + getPublicKey: typeof schnorrGetPublicKey; + sign: typeof schnorrSign; + verify: typeof schnorrVerify; + utils: { + randomPrivateKey: () => Uint8Array; + lift_x: typeof lift_x; + pointToBytes: (point: PointType) => Uint8Array; + numberToBytesBE: typeof numberToBytesBE; + bytesToNumberBE: typeof bytesToNumberBE; + taggedHash: typeof taggedHash; + mod: typeof mod; + }; +}; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts.map b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts.map new file mode 100644 index 0000000..e9284b2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAKA,OAAO,EAAS,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAGL,eAAe,EAGf,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,aAAa,IAAI,SAAS,EAAuB,MAAM,2BAA2B,CAAC;AAsC5F;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAsOqje,CAAC;;;;;;oDAAwmB,CAAC;mEAA2F,CAAC;+CAAuE,CAAC;;;;yCAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EA3L7vgB,CAAC;AAOF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAkBD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAS5C;AASD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAExD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAClB,OAAO,EAAE,GAAG,EACZ,UAAU,EAAE,OAAO,EACnB,OAAO,GAAE,GAAqB,GAC7B,UAAU,CAgBZ;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAiB5E;AAED;;GAEG;AACH,eAAO,MAAM,OAAO;;;;;;;8BAhGS,SAAS,CAAC,MAAM,CAAC;;;;;;CA6GzC,CAAC;AA0DN,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js new file mode 100644 index 0000000..6edaf13 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js @@ -0,0 +1,258 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { createCurve } from './_shortw_utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √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 = secp256k1P; + // 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 (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +export const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, 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 +const _0n = BigInt(0); +/** 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(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + 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.toRawBytes(true).slice(1); +const numTo32b = (n) => numberToBytesBE(n, 32); +const modP = (x) => mod(x, secp256k1P); +const modN = (x) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: 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) { + aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +const num = bytesToNumberBE; +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(num(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).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, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(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) + const k_ = modN(num(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + 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(numTo32b(modN(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 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, secp256k1P)) + return false; + const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!inRange(s, _1n, secp256k1N)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +/** + * Schnorr signatures over secp256k1. + */ +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [ + // 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(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js.map b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js.map new file mode 100644 index 0000000..cf7ef44 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/esm/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EACL,OAAO,EACP,QAAQ,EACR,eAAe,EACf,WAAW,EACX,WAAW,EACX,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAA8B,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAE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GAAG,EAAE,CAChC,YAAY,CACV,SAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CACF,CAAC,EAAE,CAAC;AACP,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/index.d.ts b/src/libMPC/node_modules/@noble/curves/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/index.d.ts.map b/src/libMPC/node_modules/@noble/curves/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/index.js b/src/libMPC/node_modules/@noble/curves/index.js new file mode 100644 index 0000000..da92182 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/index.js.map b/src/libMPC/node_modules/@noble/curves/index.js.map new file mode 100644 index 0000000..b6e5db7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/jubjub.d.ts b/src/libMPC/node_modules/@noble/curves/jubjub.d.ts new file mode 100644 index 0000000..7d2c398 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/jubjub.d.ts @@ -0,0 +1,9 @@ +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export declare const jubjub: import("./abstract/edwards.js").CurveFn; +export declare function groupHash(tag: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +export declare function findGroupHash(m: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +//# sourceMappingURL=jubjub.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/jubjub.d.ts.map b/src/libMPC/node_modules/@noble/curves/jubjub.d.ts.map new file mode 100644 index 0000000..7cb27ff --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/jubjub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AAEH,eAAO,MAAM,MAAM,yCAgBR,CAAC;AAOZ,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAUrE;AAKD,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAWvE"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/jubjub.js b/src/libMPC/node_modules/@noble/curves/jubjub.js new file mode 100644 index 0000000..35dce41 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/jubjub.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jubjub = void 0; +exports.groupHash = groupHash; +exports.findGroupHash = findGroupHash; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const blake2s_1 = require("@noble/hashes/blake2s"); +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +exports.jubjub = (0, edwards_js_1.twistedEdwards)({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: (0, modular_js_1.Field)(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, +}); +const GH_FIRST_BLOCK = (0, utils_1.utf8ToBytes)('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +function groupHash(tag, personalization) { + const h = blake2s_1.blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = exports.jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(exports.jubjub.CURVE.h); + if (p.equals(exports.jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +// No secret data is leaked here at all. +// It operates over public data: +// const G_SPEND = jubjub.findGroupHash(new Uint8Array(), utf8ToBytes('Item_G_')); +function findGroupHash(m, personalization) { + const tag = (0, utils_1.concatBytes)(m, new Uint8Array([0])); + const hashes = []; + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + hashes.push(groupHash(tag, personalization)); + } + catch (e) { } + } + if (!hashes.length) + throw new Error('findGroupHash tag overflow'); + return hashes[0]; +} +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/jubjub.js.map b/src/libMPC/node_modules/@noble/curves/jubjub.js.map new file mode 100644 index 0000000..ed335a5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":";;;AAoCA,8BAUC;AAKD,sCAWC;AA9DD,sEAAsE;AACtE,mDAAgD;AAChD,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAuD;AACvD,sDAA8C;AAE9C;;;;GAIG;AAEU,QAAA,MAAM,GAAmB,IAAA,2BAAc,EAAC;IACnD,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,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AC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC;YACH,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC,CAAC;QAC/C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;IAChB,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p256.d.ts b/src/libMPC/node_modules/@noble/curves/p256.d.ts new file mode 100644 index 0000000..5c02dff --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p256.d.ts @@ -0,0 +1,105 @@ +export declare const p256: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp256r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p256.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p256.d.ts.map b/src/libMPC/node_modules/@noble/curves/p256.d.ts.map new file mode 100644 index 0000000..9a2de13 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.d.ts","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiCi5xB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtBlk0B,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqB44xB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArBxj0B,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p256.js b/src/libMPC/node_modules/@noble/curves/p256.js new file mode 100644 index 0000000..d7ba3a1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p256.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp256r1 = exports.p256 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = (0, modular_js_1.Field)(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +exports.p256 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256_1.sha256); +exports.secp256r1 = exports.p256; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p256.js.map b/src/libMPC/node_modules/@noble/curves/p256.js.map new file mode 100644 index 0000000..eb8d8bc --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,yDAAiD;AACjD,kEAA2D;AAC3D,sDAA8C;AAC9C,8DAAgE;AAEhE,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE7F,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,OAAO,EAAE,wBAAwB;IACpC,CAAC,EAAE,OAAO;IACV,EAAE,EAAE,yDAAyD;IAC7D,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p384.d.ts b/src/libMPC/node_modules/@noble/curves/p384.d.ts new file mode 100644 index 0000000..aa88088 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p384.d.ts @@ -0,0 +1,105 @@ +export declare const p384: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp384r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p384.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p384.d.ts.map b/src/libMPC/node_modules/@noble/curves/p384.d.ts.map new file mode 100644 index 0000000..f6e94f1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p384.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiCqpxB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtBt0zB,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqBgpxB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArB5zzB,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p384.js b/src/libMPC/node_modules/@noble/curves/p384.js new file mode 100644 index 0000000..55e18cb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p384.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp384r1 = exports.p384 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +exports.p384 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha512_1.sha384); +exports.secp384r1 = exports.p384; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha512_1.sha384, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p384.js.map b/src/libMPC/node_modules/@noble/curves/p384.js.map new file mode 100644 index 0000000..9275527 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,yDAAiD;AACjD,kEAA2D;AAC3D,sDAA8C;AAC9C,8DAAgE;AAEhE,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,kBAAkB;AAClB,MAAM,OAAO,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AAE7H,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,OAAO,EAAE,wBAAwB;IACpC,CAAC,EAAE,OAAO;IACV,EAAE,EAAE,sDAAsD;IAC1D,yDAAyD;IACzD,CAAC,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAC/G,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,EAAE,EAAE,MAAM,CAAC,oGAAoG,CAAC;IAChH,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p521.d.ts b/src/libMPC/node_modules/@noble/curves/p521.d.ts new file mode 100644 index 0000000..26ac25b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p521.d.ts @@ -0,0 +1,105 @@ +export declare const p521: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp521r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p521.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p521.d.ts.map b/src/libMPC/node_modules/@noble/curves/p521.d.ts.map new file mode 100644 index 0000000..e3ee629 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p521.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.d.ts","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":"AAmCA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAiC4wwB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EAtB77yB,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAqBuwwB,CAAC;;;;;;kFAAwmB,CAAC;+HAA2F,CAAC;2GAAuE,CAAC;;;;qGAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EArBn7yB,CAAC;AAmB9B,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p521.js b/src/libMPC/node_modules/@noble/curves/p521.js new file mode 100644 index 0000000..7d2ebef --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p521.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp521r1 = exports.p521 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +exports.p521 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512_1.sha512); +exports.secp521r1 = exports.p521; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/p521.js.map b/src/libMPC/node_modules/@noble/curves/p521.js.map new file mode 100644 index 0000000..21d1480 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":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,EAAE,EAAE;IACtB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/package.json b/src/libMPC/node_modules/@noble/curves/package.json new file mode 100644 index 0000000..5c3b9b1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/package.json @@ -0,0 +1,167 @@ +{ + "name": "@noble/curves", + "version": "1.6.0", + "description": "Audited & minimal JS implementation of elliptic curve cryptography", + "files": [ + "abstract", + "esm", + "src", + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map" + ], + "scripts": { + "bench": "cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node hash-to-curve.js; node modular.js; node bls.js; node ristretto255.js; node decaf448.js", + "build": "tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build && npm i && npm run build", + "build:clean": "rm *.{js,d.ts,d.ts.map,js.map} esm/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/*.js'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/*.js'", + "test": "node test/index.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-curves.git" + }, + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.5.0" + }, + "devDependencies": { + "@paulmillr/jsbt": "0.2.1", + "fast-check": "3.0.0", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "3.3.2", + "typescript": "5.5.2" + }, + "sideEffects": false, + "main": "index.js", + "exports": { + ".": { + "import": "./esm/index.js", + "require": "./index.js" + }, + "./abstract/bls": { + "import": "./esm/abstract/bls.js", + "require": "./abstract/bls.js" + }, + "./abstract/curve": { + "import": "./esm/abstract/curve.js", + "require": "./abstract/curve.js" + }, + "./abstract/edwards": { + "import": "./esm/abstract/edwards.js", + "require": "./abstract/edwards.js" + }, + "./abstract/hash-to-curve": { + "import": "./esm/abstract/hash-to-curve.js", + "require": "./abstract/hash-to-curve.js" + }, + "./abstract/modular": { + "import": "./esm/abstract/modular.js", + "require": "./abstract/modular.js" + }, + "./abstract/montgomery": { + "import": "./esm/abstract/montgomery.js", + "require": "./abstract/montgomery.js" + }, + "./abstract/poseidon": { + "import": "./esm/abstract/poseidon.js", + "require": "./abstract/poseidon.js" + }, + "./abstract/tower": { + "import": "./esm/abstract/tower.js", + "require": "./abstract/tower.js" + }, + "./abstract/utils": { + "import": "./esm/abstract/utils.js", + "require": "./abstract/utils.js" + }, + "./abstract/weierstrass": { + "import": "./esm/abstract/weierstrass.js", + "require": "./abstract/weierstrass.js" + }, + "./_shortw_utils": { + "import": "./esm/_shortw_utils.js", + "require": "./_shortw_utils.js" + }, + "./bls12-381": { + "import": "./esm/bls12-381.js", + "require": "./bls12-381.js" + }, + "./bn254": { + "import": "./esm/bn254.js", + "require": "./bn254.js" + }, + "./ed25519": { + "import": "./esm/ed25519.js", + "require": "./ed25519.js" + }, + "./ed448": { + "import": "./esm/ed448.js", + "require": "./ed448.js" + }, + "./index": { + "import": "./esm/index.js", + "require": "./index.js" + }, + "./jubjub": { + "import": "./esm/jubjub.js", + "require": "./jubjub.js" + }, + "./p256": { + "import": "./esm/p256.js", + "require": "./p256.js" + }, + "./p384": { + "import": "./esm/p384.js", + "require": "./p384.js" + }, + "./p521": { + "import": "./esm/p521.js", + "require": "./p521.js" + }, + "./pasta": { + "import": "./esm/pasta.js", + "require": "./pasta.js" + }, + "./secp256k1": { + "import": "./esm/secp256k1.js", + "require": "./secp256k1.js" + } + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "keywords": [ + "elliptic", + "curve", + "cryptography", + "secp256k1", + "ed25519", + "p256", + "p384", + "p521", + "secp256r1", + "ed448", + "x25519", + "ed25519", + "bls12-381", + "bn254", + "alt_bn128", + "bls", + "noble", + "ecc", + "ecdsa", + "eddsa", + "weierstrass", + "montgomery", + "edwards", + "schnorr" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/src/libMPC/node_modules/@noble/curves/pasta.d.ts b/src/libMPC/node_modules/@noble/curves/pasta.d.ts new file mode 100644 index 0000000..9e1f4ed --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/pasta.d.ts @@ -0,0 +1,5 @@ +export declare const p: bigint; +export declare const q: bigint; +export declare const pallas: import("./abstract/weierstrass.js").CurveFn; +export declare const vesta: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=pasta.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/pasta.d.ts.map b/src/libMPC/node_modules/@noble/curves/pasta.d.ts.map new file mode 100644 index 0000000..d4e6dd5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/pasta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.d.ts","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,CAAC,QAA+E,CAAC;AAC9F,eAAO,MAAM,CAAC,QAA+E,CAAC;AAG9F,eAAO,MAAM,MAAM,6CASjB,CAAC;AAEH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/pasta.js b/src/libMPC/node_modules/@noble/curves/pasta.js new file mode 100644 index 0000000..c531e75 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/pasta.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.vesta = exports.pallas = exports.q = exports.p = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +exports.p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +exports.q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +exports.pallas = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: (0, modular_js_1.Field)(exports.p), + n: exports.q, + Gx: (0, modular_js_1.mod)(BigInt(-1), exports.p), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +// https://neuromancer.sk/std/other/Vesta +exports.vesta = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: (0, modular_js_1.Field)(exports.q), + n: exports.p, + Gx: (0, modular_js_1.mod)(BigInt(-1), exports.q), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/pasta.js.map b/src/libMPC/node_modules/@noble/curves/pasta.js.map new file mode 100644 index 0000000..3edeb3e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,yDAA6C;AAC7C,sDAAmD;AACnD,8DAAwD;AAE3C,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AACjF,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC7B,QAAA,MAAM,GAAG,IAAA,4BAAW,EAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,IAAA,kBAAK,EAAC,SAAC,CAAC;IACZ,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,IAAA,gBAAG,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IACtB,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AAC5B,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,IAAA,kBAAK,EAAC,SAAC,CAAC;IACZ,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,IAAA,gBAAG,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IACtB,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts b/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts new file mode 100644 index 0000000..1458b4e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts @@ -0,0 +1,99 @@ +import { mod } from './abstract/modular.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, numberToBytesBE } from './abstract/utils.js'; +import { ProjPointType as PointType } from './abstract/weierstrass.js'; +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +export declare const secp256k1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: ReturnType<(curve: import("./abstract/weierstrass.js").CurveType) => Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[]; + readonly wrapPrivateKey?: boolean; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + }; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => PointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number) => Uint8Array; + lowS: boolean; + readonly bits2int?: (bytes: Uint8Array) => bigint; + readonly bits2int_modN?: (bytes: Uint8Array) => bigint; + readonly p: bigint; + }>>; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: Hex | { + r: bigint; + s: bigint; + }, msgHash: Hex, publicKey: Hex, opts?: import("./abstract/weierstrass.js").VerOpts) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: PointType) => PointType; + }; +}>; +declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +declare function schnorrGetPublicKey(privateKey: Hex): Uint8Array; +/** + * 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. + */ +declare function schnorrSign(message: Hex, privateKey: PrivKey, auxRand?: Hex): Uint8Array; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean; +/** + * Schnorr signatures over secp256k1. + */ +export declare const schnorr: { + getPublicKey: typeof schnorrGetPublicKey; + sign: typeof schnorrSign; + verify: typeof schnorrVerify; + utils: { + randomPrivateKey: () => Uint8Array; + lift_x: typeof lift_x; + pointToBytes: (point: PointType) => Uint8Array; + numberToBytesBE: typeof numberToBytesBE; + bytesToNumberBE: typeof bytesToNumberBE; + taggedHash: typeof taggedHash; + mod: typeof mod; + }; +}; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts) => import("./abstract/hash-to-curve.js").H2CPoint; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts.map b/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts.map new file mode 100644 index 0000000..d54a071 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/secp256k1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAKA,OAAO,EAAS,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAGL,eAAe,EAGf,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,aAAa,IAAI,SAAS,EAAuB,MAAM,2BAA2B,CAAC;AAsC5F;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0CAsOqje,CAAC;;;;;;oDAAwmB,CAAC;mEAA2F,CAAC;+CAAuE,CAAC;;;;yCAAoH,CAAC;;;;;;;+BAA+R,CAAC,eAAe,CAAC;;EA3L7vgB,CAAC;AAOF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAkBD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAS5C;AASD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAExD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAClB,OAAO,EAAE,GAAG,EACZ,UAAU,EAAE,OAAO,EACnB,OAAO,GAAE,GAAqB,GAC7B,UAAU,CAgBZ;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAiB5E;AAED;;GAEG;AACH,eAAO,MAAM,OAAO;;;;;;;8BAhGS,SAAS,CAAC,MAAM,CAAC;;;;;;CA6GzC,CAAC;AA0DN,eAAO,MAAM,WAAW,2IAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,2IAA8C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/secp256k1.js b/src/libMPC/node_modules/@noble/curves/secp256k1.js new file mode 100644 index 0000000..0d53d2f --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/secp256k1.js @@ -0,0 +1,261 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const modular_js_1 = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √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 = secp256k1P; + // 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 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P; + const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P; + const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P; + const root = (0, modular_js_1.pow2)(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n); + let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256_1.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 +const _0n = BigInt(0); +/** 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 = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = (0, utils_js_1.concatBytes)(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32); +const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P); +const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N); +const Point = exports.secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: 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) { + (0, utils_js_1.aInRange)('x', x, _1n, secp256k1P); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +const num = utils_js_1.bytesToNumberBE; +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(num(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).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, privateKey, auxRand = (0, utils_1.randomBytes)(32)) { + const m = (0, utils_js_1.ensureBytes)('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(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) + const k_ = modN(num(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + 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(numTo32b(modN(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 sig = (0, utils_js_1.ensureBytes)('signature', signature, 64); + const m = (0, utils_js_1.ensureBytes)('message', message); + const pub = (0, utils_js_1.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 (!(0, utils_js_1.inRange)(r, _1n, secp256k1P)) + return false; + const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!(0, utils_js_1.inRange)(s, _1n, secp256k1N)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +/** + * Schnorr signatures over secp256k1. + */ +exports.schnorr = (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: exports.secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE: utils_js_1.numberToBytesBE, + bytesToNumberBE: utils_js_1.bytesToNumberBE, + taggedHash, + mod: modular_js_1.mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // 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__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/secp256k1.js.map b/src/libMPC/node_modules/@noble/curves/secp256k1.js.map new file mode 100644 index 0000000..938cb47 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAAkD;AAClD,yDAAiD;AACjD,kEAAuE;AACvE,sDAAyD;AAEzD,kDAO6B;AAC7B,8DAA4F;AAE5F,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,U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,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EACV,iBAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/curves/src/_shortw_utils.ts b/src/libMPC/node_modules/@noble/curves/src/_shortw_utils.ts new file mode 100644 index 0000000..45b350c --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/_shortw_utils.ts @@ -0,0 +1,20 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { CHash } from './abstract/utils.js'; +import { CurveType, weierstrass } from './abstract/weierstrass.js'; + +// connects noble-curves to noble-hashes +export function getHash(hash: CHash) { + return { + hash, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +// Same API as @noble/hashes, with ability to create curve with custom hash +type CurveDef = Readonly>; +export function createCurve(curveDef: CurveDef, defHash: CHash) { + const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/bls.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/bls.ts new file mode 100644 index 0000000..f71c44f --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/bls.ts @@ -0,0 +1,556 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. +// TODO: import { AffinePoint } from './curve.js'; +import { IField, getMinHashLength, mapHashToField } from './modular.js'; +import { Hex, PrivKey, CHash, ensureBytes, memoized } from './utils.js'; +// prettier-ignore +import { + MapToCurve, Opts as HTFOpts, H2CPointConstructor, htfBasicOpts, + createHasher +} from './hash-to-curve.js'; +import { + CurvePointsType, + ProjPointType as ProjPointType, + CurvePointsRes, + weierstrassPoints, +} from './weierstrass.js'; +import type { Fp2, Fp6, Fp12, Fp2Bls, Fp12Bls } from './tower.js'; + +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two main ways to use it: + * 1. Fp for short private keys, Fp₂ for signatures + * 2. Fp for short signatures, Fp₂ for private keys + **/ + +type Fp = bigint; // Can be different field? + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); + +export type TwistType = 'multiplicative' | 'divisive'; + +export type ShortSignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; + +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; + +export type CurveType = { + G1: Omit, 'n'> & { + ShortSignature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: MapToCurve; + htfDefaults: HTFOpts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + }; + params: { + // NOTE: MSB is always ignored and used as marker for length, + // otherwise leading zeros will be lost. + // Can be different from 'X' (seed) param! + ateLoopSize: bigint; + xNegative: boolean; + r: bigint; + twistType: TwistType; // BLS12-381: Multiplicative, BN254: Divisive + }; + htfDefaults: HTFOpts; + hash: CHash; // Because we need outputLen for DRBG + randomBytes: (bytesLength?: number) => Uint8Array; + // This is super ugly hack for untwist point in BN254 after miller loop + postPrecompute?: ( + Rx: Fp2, + Ry: Fp2, + Rz: Fp2, + Qx: Fp2, + Qy: Fp2, + pointAdd: (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => { Rx: Fp2; Ry: Fp2; Rz: Fp2 } + ) => void; +}; + +type PrecomputeSingle = [Fp2, Fp2, Fp2][]; +type Precompute = PrecomputeSingle[]; + +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + getPublicKeyForShortSignatures: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + signShortSignature: { + (message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + (message: ProjPointType, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType; + }; + verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType, + htfOpts?: htfBasicOpts + ) => boolean; + verifyShortSignature: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType, + htfOpts?: htfBasicOpts + ) => boolean; + verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[], + htfOpts?: htfBasicOpts + ) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + aggregateShortSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + pairingBatch: ( + pairs: { g1: ProjPointType; g2: ProjPointType }[], + withFinalExponent?: boolean + ) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + ShortSignature: ShortSignatureCoder; + params: { + ateLoopSize: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: Fp2Bls; + Fp6: IField; + Fp12: Fp12Bls; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: ProjPointType) => Precompute; + }; +}; + +// Not used with BLS12-381 (no sequential `11` in X). Useful for other curves. +function NAfDecomposition(a: bigint) { + const res = []; + // a>1 because of marker bit + for (; a > _1n; a >>= _1n) { + if ((a & _1n) === _0n) res.unshift(0); + else if ((a & _3n) === _3n) { + res.unshift(-1); + a += _1n; + } else res.unshift(1); + } + return res; +} + +export function bls(CURVE: CurveType): CurveFn { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_IS_NEGATIVE = CURVE.params.xNegative; + const TWIST: TwistType = CURVE.params.twistType; + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign( + G1_, + createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + }) + ); + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign( + G2_, + createHasher(G2_.ProjectivePoint as H2CPointConstructor, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + }) + ); + type G1 = typeof G1.ProjectivePoint.BASE; + type G2 = typeof G2.ProjectivePoint.BASE; + + // Applies sparse multiplication as line function + let lineFunction: (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => Fp12; + if (TWIST === 'multiplicative') { + lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => + Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); + } else if (TWIST === 'divisive') { + // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of + // precompute calculations. + lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => + Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); + } else throw new Error('bls: unknown twist type'); + + const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n)); + function pointDouble(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2) { + const t0 = Fp2.sqr(Ry); // Ry² + const t1 = Fp2.sqr(Rz); // Rz² + const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + const t3 = Fp2.mul(t2, _3n); // 3 * T2 + const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + const c0 = Fp2.sub(t2, t0); // T2 - T0 (i) + const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx² + const c2 = Fp2.neg(t4); // -T4 (-h) + + ell.push([c0, c1, c2]); + + Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + return { Rx, Ry, Rz }; + } + function pointAdd(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) { + // Addition + const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy + const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry + const c2 = t1; // == Rx - Qx * Rz + + ell.push([c0, c1, c2]); + + const t2 = Fp2.sqr(t1); // T1² + const t3 = Fp2.mul(t2, t1); // T2 * T1 + const t4 = Fp2.mul(t2, Rx); // T2 * Rx + const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + return { Rx, Ry, Rz }; + } + + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine + // add + double in windowed precomputes here, otherwise it would be single op (since X is static) + const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize); + + const calcPairingPrecomputes = memoized((point: G2) => { + const p = point; + const { x, y } = p.toAffine(); + // prettier-ignore + const Qx = x, Qy = y, negQy = Fp2.neg(y); + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; + const ell: Precompute = []; + for (const bit of ATE_NAF) { + const cur: PrecomputeSingle = []; + ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); + if (bit) ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); + ell.push(cur); + } + if (CURVE.postPrecompute) { + const last = ell[ell.length - 1]; + CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); + } + return ell; + }); + + // Main pairing logic is here. Computes product of miller loops + final exponentiate + // Applies calculated precomputes + type MillerInput = [Precompute, Fp, Fp][]; + function millerLoopBatch(pairs: MillerInput, withFinalExponent: boolean = false) { + let f12 = Fp12.ONE; + if (pairs.length) { + const ellLen = pairs[0][0].length; + for (let i = 0; i < ellLen; i++) { + f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings + // NOTE: we apply multiple pairings in parallel here + for (const [ell, Px, Py] of pairs) { + for (const [c0, c1, c2] of ell[i]) f12 = lineFunction(c0, c1, c2, f12, Px, Py); + } + } + } + if (BLS_X_IS_NEGATIVE) f12 = Fp12.conjugate(f12); + return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; + } + type PairingInput = { g1: G1; g2: G2 }; + // Calculates product of multiple pairings + // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))` + function pairingBatch(pairs: PairingInput[], withFinalExponent: boolean = true) { + const res: MillerInput = []; + // This cache precomputed toAffine for all points + G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1)); + G2.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2)); + for (const { g1, g2 } of pairs) { + if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + // This uses toAffine inside + g1.assertValidity(); + g2.assertValidity(); + const Qa = g1.toAffine(); + res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]); + } + return millerLoopBatch(res, withFinalExponent); + } + // Calculates bilinear pairing + function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 { + return pairingBatch([{ g1: Q, g2: P }], withFinalExponent); + } + + const utils = { + randomPrivateKey: (): Uint8Array => { + const length = getMinHashLength(Fr.ORDER); + return mapHashToField(CURVE.randomBytes(length), Fr.ORDER); + }, + calcPairingPrecomputes, + }; + + const { ShortSignature } = CURVE.G1; + const { Signature } = CURVE.G2; + + type G1Hex = Hex | G1; + type G2Hex = Hex | G2; + function normP1(point: G1Hex): G1 { + return point instanceof G1.ProjectivePoint ? (point as G1) : G1.ProjectivePoint.fromHex(point); + } + function normP1Hash(point: G1Hex, htfOpts?: htfBasicOpts): G1 { + return point instanceof G1.ProjectivePoint + ? point + : (G1.hashToCurve(ensureBytes('point', point), htfOpts) as G1); + } + function normP2(point: G2Hex): G2 { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point: G2Hex, htfOpts?: htfBasicOpts): G2 { + return point instanceof G2.ProjectivePoint + ? point + : (G2.hashToCurve(ensureBytes('point', point), htfOpts) as G2); + } + + // Multiplies generator (G1) by private key. + // P = pk x G + function getPublicKey(privateKey: PrivKey): Uint8Array { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + + // Multiplies generator (G2) by private key. + // P = pk x G + function getPublicKeyForShortSignatures(privateKey: PrivKey): Uint8Array { + return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + + // Executes `hashToCurve` on the message and then multiplies the result by private key. + // S = pk x H(m) + function sign(message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array; + function sign(message: G2, privateKey: PrivKey, htfOpts?: htfBasicOpts): G2; + function sign(message: G2Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array | G2 { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) return sigPoint; + return Signature.toRawBytes(sigPoint); + } + + function signShortSignature( + message: Hex, + privateKey: PrivKey, + htfOpts?: htfBasicOpts + ): Uint8Array; + function signShortSignature(message: G1, privateKey: PrivKey, htfOpts?: htfBasicOpts): G1; + function signShortSignature( + message: G1Hex, + privateKey: PrivKey, + htfOpts?: htfBasicOpts + ): Uint8Array | G1 { + const msgPoint = normP1Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G1.ProjectivePoint) return sigPoint; + return ShortSignature.toRawBytes(sigPoint); + } + + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify( + signature: G2Hex, + message: G2Hex, + publicKey: G1Hex, + htfOpts?: htfBasicOpts + ): boolean { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + const exp = pairingBatch([ + { g1: P.negate(), g2: Hm }, // ePHM = pairing(P.negate(), Hm, false); + { g1: G, g2: S }, // eGS = pairing(G, S, false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(S, G) == e(H(m), P) + function verifyShortSignature( + signature: G1Hex, + message: G1Hex, + publicKey: G2Hex, + htfOpts?: htfBasicOpts + ): boolean { + const P = normP2(publicKey); + const Hm = normP1Hash(message, htfOpts); + const G = G2.ProjectivePoint.BASE; + const S = normP1(signature); + const exp = pairingBatch([ + { g1: Hm, g2: P }, // eHmP = pairing(Hm, P, false); + { g1: S, g2: G.negate() }, // eSG = pairing(S, G.negate(), false); + ]); + return Fp12.eql(exp, Fp12.ONE); + } + + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + function aggregatePublicKeys(publicKeys: Hex[]): Uint8Array; + function aggregatePublicKeys(publicKeys: G1[]): G1; + function aggregatePublicKeys(publicKeys: G1Hex[]): Uint8Array | G1 { + if (!publicKeys.length) throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + + // Adds a bunch of signature points together. + function aggregateSignatures(signatures: Hex[]): Uint8Array; + function aggregateSignatures(signatures: G2[]): G2; + function aggregateSignatures(signatures: G2Hex[]): Uint8Array | G2 { + if (!signatures.length) throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + + // Adds a bunch of signature points together. + function aggregateShortSignatures(signatures: Hex[]): Uint8Array; + function aggregateShortSignatures(signatures: G1[]): G1; + function aggregateShortSignatures(signatures: G1Hex[]): Uint8Array | G1 { + if (!signatures.length) throw new Error('Expected non-empty array'); + const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return ShortSignature.toRawBytes(aggAffine); + } + + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch( + signature: G2Hex, + // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead? + messages: G2Hex[], + publicKeys: G1Hex[], + htfOpts?: htfBasicOpts + ): boolean { + if (!messages.length) throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + // NOTE: this works only for exact same object + const messagePubKeyMap = new Map(); + for (let i = 0; i < nPublicKeys.length; i++) { + const pub = nPublicKeys[i]; + const msg = nMessages[i]; + let keys = messagePubKeyMap.get(msg); + if (keys === undefined) { + keys = []; + messagePubKeyMap.set(msg, keys); + } + keys.push(pub); + } + const paired = []; + try { + for (const [msg, keys] of messagePubKeyMap) { + const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg)); + paired.push({ g1: groupPublicKey, g2: msg }); + } + paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig }); + return Fp12.eql(pairingBatch(paired), Fp12.ONE); + } catch { + return false; + } + } + + G1.ProjectivePoint.BASE._setWindowSize(4); + + return { + getPublicKey, + getPublicKeyForShortSignatures, + sign, + signShortSignature, + verify, + verifyBatch, + verifyShortSignature, + aggregatePublicKeys, + aggregateSignatures, + aggregateShortSignatures, + millerLoopBatch, + pairing, + pairingBatch, + G1, + G2, + Signature, + ShortSignature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + ateLoopSize: CURVE.params.ateLoopSize, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/curve.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/curve.ts new file mode 100644 index 0000000..972f0af --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/curve.ts @@ -0,0 +1,275 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { IField, validateField, nLength } from './modular.js'; +import { validateObject, bitLen } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); + +export type AffinePoint = { + x: T; + y: T; +} & { z?: never; t?: never }; + +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} + +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; + +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) + +// Elliptic curve multiplication of Point by scalar. Fragile. +// 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 function wNAF>(c: GroupConstructor, bits: number) { + const constTimeNegate = (condition: boolean, item: T): T => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W: number) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W: number) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm: T, n: bigint) { + let p = c.ZERO; + let d: T = 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. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[] { + const { windows, windowSize } = opts(W); + const points: T[] = []; + let p: T = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + 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. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + + let p = c.ZERO; + let f = c.BASE; + + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + + // Shift number by W bits. + n >>= shiftBy; + + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + + // 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. + + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // 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 }; + }, + + wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T } { + const W: number = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W) as T[]; + if (W !== 1) pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // 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. + + setWindowSize(P: T, W: number) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} + +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with 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 field 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 private keys / bigints) + */ +export function pippenger>( + c: GroupConstructor, + field: IField, + points: T[], + scalars: bigint[] +): T { + // 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 + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof (c as any))) throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.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 = c.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 as T; +} + +// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok. +// Though generator can be different (Fp2 / Fp6 for BLS). +export type BasicCurve = { + Fp: IField; // Field over which we'll do calculations (Fp) + n: bigint; // Curve order, total count of valid points in the field + nBitLength?: number; // bit length of curve order + nByteLength?: number; // byte length of curve order + h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation + hEff?: bigint; // Number to multiply to clear cofactor + Gx: T; // base point X coordinate + Gy: T; // base point Y coordinate + allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey +}; + +export function validateBasic(curve: BasicCurve & T) { + 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 }, + } as const); +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/edwards.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/edwards.ts new file mode 100644 index 0000000..d90901e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/edwards.ts @@ -0,0 +1,541 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { + AffinePoint, + BasicCurve, + Group, + GroupConstructor, + validateBasic, + wNAF, + pippenger, +} from './curve.js'; +import { mod, Field } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, FHash, Hex, memoized, abool } from './utils.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); + +// Edwards curves must declare params a & d. +export type CurveType = BasicCurve & { + a: bigint; // curve param a + d: bigint; // curve param d + hash: FHash; // Hashing + randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing + uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v) + prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify() + mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard +}; + +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + curve, + { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, + { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + } + ); + // Set defaults + return Object.freeze({ ...opts } as const); +} + +// Instance of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; + msm(points: ExtPointType[], scalars: bigint[]): ExtPointType; +} + +/** + * Edwards Curve interface. + * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`. + */ +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array; + verify: ( + sig: Hex, + message: Hex, + publicKey: Hex, + options?: { context?: Hex; zip215: boolean } + ) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; + +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +export function twistedEdwards(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { + Fp, + n: CURVE_ORDER, + prehash: prehash, + hash: cHash, + randomBytes, + nByteLength, + h: cofactor, + } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + + // sqrt(u/v) + const uvRatio = + CURVE.uvRatio || + ((u: bigint, v: bigint) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP + const domain = + CURVE.domain || + ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + abool('phflag', phflag); + if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title: string, n: bigint) { + ut.aInRange('coordinate ' + title, n, _0n, MASK); + } + + function assertPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) return { x: _0n, y: _1n }; + if (zz !== _1n) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p: Point) => { + const { a, d } = CURVE; + if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) throw new Error('bad point: equation left != right (2)'); + return true; + }); + + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point implements ExtPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + + constructor( + readonly ex: bigint, + readonly ey: bigint, + readonly ez: bigint, + readonly et: bigint + ) { + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + static fromAffine(p: AffinePoint): Point { + if (p instanceof Point) throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points: Point[], scalars: bigint[]) { + return pippenger(Point, Fn, points, scalars); + } + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity(): void { + assertValidMemo(this); + } + + // Compare one point to another. + equals(other: Point): boolean { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + + is0(): boolean { + return this.equals(Point.ZERO); + } + + negate(): Point { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double(): Point { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other: Point) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + + return new Point(X3, Y3, Z3, T3); + } + + subtract(other: Point): Point { + return this.add(other.negate()); + } + + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + + // Constant-time multiplication. + multiply(scalar: bigint): Point { + const n = scalar; + ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[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 private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar: bigint): Point { + const n = scalar; + ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n) return I; + if (this.equals(I) || n === _1n) return this; + if (this.equals(G)) return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder(): boolean { + return this.multiplyUnsafe(cofactor).is0(); + } + + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree(): boolean { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz?: bigint): AffinePoint { + return toAffineMemo(this, iz); + } + + clearCofactor(): Point { + const { h: cofactor } = CURVE; + if (cofactor === _1n) return this; + return this.multiplyUnsafe(cofactor); + } + + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex: Hex, zip215 = false): Point { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + ut.aInRange('pointHex.y', y, _0n, max); + + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey: Hex) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes(): Uint8Array { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex(): string { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + + function modN(a: bigint) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash: Uint8Array): bigint { + return modN(ut.bytesToNumberLE(hash)); + } + + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key: Hex) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey: Hex): Uint8Array { + return getExtendedPublicKey(privKey).pointBytes; + } + + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array { + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + + const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT; + function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) abool('zip215', zip215); + if (prehash) msg = prehash(msg); // for ed25519ph, etc + + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) return false; + + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES), + + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/hash-to-curve.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/hash-to-curve.ts new file mode 100644 index 0000000..576aa8b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/hash-to-curve.ts @@ -0,0 +1,233 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { AffinePoint, Group, GroupConstructor } from './curve.js'; +import { IField, mod } from './modular.js'; +import type { CHash } from './utils.js'; +import { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js'; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; + +// 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: number, length: number): Uint8Array { + anum(value); + anum(length); + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0) as number[]; + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} + +function strxor(a: Uint8Array, b: Uint8Array): Uint8Array { + 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: unknown): void { + if (!Number.isSafeInteger(item)) throw new Error('number expected'); +} + +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +export function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array { + abytes(msg); + abytes(DST); + anum(lenInBytes); + // 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. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +export function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array { + abytes(msg); + abytes(DST); + anum(lenInBytes); + // 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 + * 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: Uint8Array, count: number, options: Opts): bigint[][] { + validateObject(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + abytes(msg); + anum(count); + const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST; + 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: F, map: [T[], T[], T[], T[]]) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x: T, y: T) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => + val.reduce((acc, i) => field.add(field.mul(acc, x), i)) + ); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} + +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} + +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} + +export type MapToCurve = (scalar: bigint[]) => AffinePoint; + +// Separated from initialization opts, so users won't accidentally change per-curve parameters +// (changing DST is ok!) +export type htfBasicOpts = { DST: UnicodeOrBytes }; + +export function createHasher( + Point: H2CPointConstructor, + mapToCurve: MapToCurve, + def: Opts & { encodeDST?: UnicodeOrBytes } +) { + if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars: bigint[]) { + if (!Array.isArray(scalars)) throw new Error('mapToCurve: expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') + throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); + const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/modular.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/modular.ts new file mode 100644 index 0000000..5299324 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/modular.ts @@ -0,0 +1,494 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { + bitMask, + bytesToNumberBE, + bytesToNumberLE, + ensureBytes, + numberToBytesBE, + numberToBytesLE, + validateObject, +} from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); + +// Calculates a modulo b +export function mod(a: bigint, b: bigint): bigint { + 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 + */ +// TODO: use field version && remove +export function pow(num: bigint, power: bigint, modulo: bigint): bigint { + if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} + +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x: bigint, power: bigint, modulo: bigint): bigint { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} + +// Inverses number over modulo +export function invert(number: bigint, modulo: bigint): bigint { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // 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); +} + +/** + * 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 + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +export function tonelliShanks(P: bigint) { + // Legendre constant: 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) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + + let Q: bigint, S: number, Z: bigint; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++); + + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++); + + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp: IField, n: T): T { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} + +export function FpSqrt(P: bigint) { + // NOTE: 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). + + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp: IField, n: T) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + 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)); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(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 + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 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.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} + +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n; + +// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + // 1-arg + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + // 2-args + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + // N for NonNormalized (for now) + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + + // Optional + // Should be same as sgn0 function in + // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1). + // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway. + isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2 + // legendre?(num: T): T; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + // If c is False, CMOV returns a, otherwise it returns b. + cmov(a: T, b: T, c: boolean): T; +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +] as const; +export function validateField(field: IField) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + } as Record; + const opts = FIELD_FIELDS.reduce((map, val: string) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} + +// 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(f: IField, num: T, power: bigint): T { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) throw new Error('Expected power > 0'); + if (power === _0n) return f.ONE; + if (power === _1n) return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} + +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +export function FpInvertBatch(f: IField, nums: T[]): T[] { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} + +export function FpDiv(f: IField, lhs: T, rhs: T | bigint): T { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} + +export function FpLegendre(order: bigint) { + // (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) + const legendreConst = (order - _1n) / _2n; // Integer arithmetic + return (f: IField, x: T): T => f.pow(x, legendreConst); +} + +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f: IField) { + const legendre = FpLegendre(f.ORDER); + return (x: T): boolean => { + const p = legendre(f, x); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} + +// CURVE.n lengths +export function nLength(n: bigint, nBitLength?: number) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} + +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * 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 doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field( + ORDER: bigint, + bitLen?: number, + isLE = false, + redef: Partial> = {} +): Readonly { + if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f: Readonly = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + 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, + 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: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + } as FpField); + return Object.freeze(f); +} + +export function FpSqrtOdd(Fp: IField, elm: T) { + 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: IField, elm: T) { + 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: string | Uint8Array, + groupOrder: bigint, + isLE = false +): bigint { + 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: bigint): number { + 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: bigint): number { + 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: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array { + 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 ? bytesToNumberBE(key) : bytesToNumberLE(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); +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/montgomery.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/montgomery.ts new file mode 100644 index 0000000..dda9ae6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/montgomery.ts @@ -0,0 +1,188 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { + aInRange, + bytesToNumberLE, + ensureBytes, + numberToBytesLE, + validateObject, +} from './utils.js'; + +const _0n = BigInt(0); +const _1n = BigInt(1); +type Hex = string | Uint8Array; + +export type CurveType = { + P: bigint; // finite field prime + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { randomPrivateKey: () => Uint8Array }; + GuBytes: Uint8Array; +}; + +function validateOpts(curve: CurveType) { + validateObject( + curve, + { + a: 'bigint', + }, + { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + } + ); + // Set defaults + return Object.freeze({ ...curve } as const); +} + +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n: bigint) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P)); + + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u: bigint, scalar: bigint): bigint { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw: [bigint, bigint]; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + + function encodeUCoordinate(u: bigint): Uint8Array { + return numberToBytesLE(modP(u), montgomeryBytes); + } + + function decodeUCoordinate(uEnc: Hex): bigint { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n: Hex): bigint { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar: Hex, u: Hex): Uint8Array { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar: Hex): Uint8Array { + return scalarMult(scalar, GuBytes); + } + + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/poseidon.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/poseidon.ts new file mode 100644 index 0000000..82d3dcd --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/poseidon.ts @@ -0,0 +1,118 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { FpPow, IField, validateField } from './modular.js'; +// We don't provide any constants, since different implementations use different constants. +// For reference constants see './test/poseidon.test.js'. +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; // Hack for stark + mds: bigint[][]; + roundConstants: bigint[][]; +}; + +export function validateOpts(opts: PoseidonOpts) { + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) throw new Error('Poseidon: wrong MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`); + + if (roundsFull % 2 !== 0) throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`); + const rounds = roundsFull + roundsPartial; + + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + + if (!sboxPower || ![3, 5, 7].includes(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds }); +} + +export function splitConstants(rc: bigint[], t: number) { + if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} + +export function poseidon(opts: PoseidonOpts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + + if (isFull) values = values.map((i) => sboxFn(i)); + else values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values: bigint[]) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = roundConstants; + return poseidonHash; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/tower.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/tower.ts new file mode 100644 index 0000000..8eb82f5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/tower.ts @@ -0,0 +1,605 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import { bitLen, bitMask, concatBytes, notImplemented } from './utils.js'; +import type { ProjConstructor, ProjPointType } from './weierstrass.js'; + +/* +Towered extension fields + +Rather than implementing a massive 12th-degree extension directly, it is more efficient +to build it up from smaller extensions: a tower of extensions. + +For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, +on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + +For more info: "Pairings for beginners" by Costello, section 7.3. +*/ + +// 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); + +// Fp₂ over complex plane +export type BigintTuple = [bigint, bigint]; +export type Fp = bigint; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +export type Fp2 = { c0: bigint; c1: bigint }; +export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +export type Fp6 = { c0: Fp2; c1: Fp2; c2: Fp2 }; +export type Fp12 = { c0: Fp6; c1: Fp6 }; // Fp₁₂ = Fp₆² => Fp₂³, Fp₆(w) / (w² - γ) where γ = v +// prettier-ignore +export type BigintTwelve = [ + bigint, bigint, bigint, bigint, bigint, bigint, + bigint, bigint, bigint, bigint, bigint, bigint +]; + +export type Fp2Bls = mod.IField & { + reim: (num: Fp2) => { re: Fp; im: Fp }; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + fromBigTuple(num: [bigint, bigint]): Fp2; +}; + +export type Fp12Bls = mod.IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; +}; + +function calcFrobeniusCoefficients( + Fp: mod.IField, + nonResidue: T, + modulus: bigint, + degree: number, + num: number = 1, + divisor?: number +) { + const _divisor = BigInt(divisor === undefined ? degree : divisor); + const towerModulus: any = modulus ** BigInt(degree); + const res: T[][] = []; + for (let i = 0; i < num; i++) { + const a = BigInt(i + 1); + const powers: T[] = []; + for (let j = 0, qPower = _1n; j < degree; j++) { + const power = ((a * qPower - a) / _divisor) % towerModulus; + powers.push(Fp.pow(nonResidue, power)); + qPower *= modulus; + } + res.push(powers); + } + return res; +} + +// This works same at least for bls12-381, bn254 and bls12-377 +export function psiFrobenius(Fp: mod.IField, Fp2: Fp2Bls, base: Fp2) { + // Ψ endomorphism + const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3) + const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2) + function psi(x: Fp2, y: Fp2): [Fp2, Fp2] { + // This x10 faster than previous version in bls12-381 + const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X); + const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y); + return [x2, y2]; + } + // Ψ²(P) endomorphism (psi2(x) = psi(psi(x))) + const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3) + // This equals -1, which causes y to be Fp2.neg(y). + // But not sure if there are case when this is not true? + const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/3) + if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) throw new Error('psiFrobenius: PSI2_Y!==-1'); + function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] { + return [Fp2.mul(x, PSI2_X), Fp2.neg(y)]; + } + // Map points + const mapAffine = + (fn: (x: T, y: T) => [T, T]) => + (c: ProjConstructor, P: ProjPointType) => { + const affine = P.toAffine(); + const p = fn(affine.x, affine.y); + return c.fromAffine({ x: p[0], y: p[1] }); + }; + const G2psi = mapAffine(psi); + const G2psi2 = mapAffine(psi2); + return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y }; +} + +export type Tower12Opts = { + ORDER: bigint; + NONRESIDUE?: Fp; + // Fp2 + FP2_NONRESIDUE: BigintTuple; + Fp2sqrt?: (num: Fp2) => Fp2; + Fp2mulByB: (num: Fp2) => Fp2; + // Fp12 + Fp12cyclotomicSquare: (num: Fp12) => Fp12; + Fp12cyclotomicExp: (num: Fp12, n: bigint) => Fp12; + Fp12finalExponentiate: (num: Fp12) => Fp12; +}; + +export function tower12(opts: Tower12Opts) { + const { ORDER } = opts; + // Fp + const Fp = mod.Field(ORDER); + const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1)); + const FpLegendre = mod.FpLegendre(ORDER); + const Fpdiv2 = Fp.div(Fp.ONE, _2n); // 1/2 + + // Fp2 + const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0]; + const Fp2Add = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), + }); + const Fp2Subtract = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), + }); + const Fp2Multiply = ({ c0, c1 }: Fp2, rhs: Fp2) => { + if (typeof rhs === 'bigint') return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; + }; + const Fp2Square = ({ c0, c1 }: Fp2) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; + }; + type Fp2Utils = { + NONRESIDUE: Fp2; + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { re: bigint; im: bigint }; + mulByNonresidue: (num: Fp2) => Fp2; + mulByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + const Fp2fromBigTuple = (tuple: BigintTuple | bigint[]) => { + if (tuple.length !== 2) throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)) as [Fp, Fp]; + return { c0: fps[0], c1: fps[1] }; + }; + + const FP2_ORDER = ORDER * ORDER; + const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE); + const Fp2: mod.IField & Fp2Utils = { + ORDER: FP2_ORDER, + NONRESIDUE: Fp2Nonresidue, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => + Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (opts.Fp2sqrt) return opts.Fp2sqrt(num); + // This is generic for all quadratic extensions (Fp2) + const { c0, c1 } = num; + if (Fp.is0(c1)) { + // if c0 is quadratic residue + if (Fp.eql(FpLegendre(Fp, c0), Fp.ONE)) return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO }); + else return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) }); + } + const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE))); + let d = Fp.mul(Fp.add(a, c0), Fpdiv2); + const legendre = FpLegendre(Fp, d); + // -1, Quadratic non residue + if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE)) d = Fp.sub(d, a); + const a0 = Fp.sqrt(d); + const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) }); + if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) throw new Error('Cannot find square root'); + // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num + const x1 = candidateSqrt; + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; + return x2; + }, + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd: (x: Fp2) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b: Uint8Array): Fp2 { + if (b.length !== Fp2.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatBytes(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue), + mulByB: opts.Fp2mulByB, + fromBigTuple: Fp2fromBigTuple, + frobeniusMap: ({ c0, c1 }, power: number): Fp2 => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), + }; + // Fp6 + const Fp6Add = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), + }); + const Fp6Subtract = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), + }); + const Fp6Multiply = ({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add( + t0, + Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2))) + ), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add( + Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), + Fp2.mulByNonresidue(t2) + ), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; + }; + const Fp6Square = ({ c0, c1, c2 }: Fp6) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; + }; + type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + mul1(num: Fp6, b1: Fp2): Fp6; + mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + mulByFp2(lhs: Fp6, rhs: Fp2): Fp6; + }; + + const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients( + Fp2, + Fp2Nonresidue, + Fp.ORDER, + 6, + 2, + 3 + ); + + const Fp6: mod.IField & Fp6Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => + Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: notImplemented, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => + Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv( + Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)) + ); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b: Uint8Array): Fp6 => { + if (b.length !== Fp6.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }): Uint8Array => + concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + fromBigSix: (t: BigintSix): Fp6 => { + if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power: number) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByFp2: ({ c0, c1, c2 }, rhs: Fp2): Fp6 => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + mul1: ({ c0, c1, c2 }, b1: Fp2): Fp6 => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + mul01({ c0, c1, c2 }, b0: Fp2, b1: Fp2): Fp6 { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + }; + + // Fp12 + const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients( + Fp2, + Fp2Nonresidue, + Fp.ORDER, + 12, + 1, + 6 + )[0]; + + const Fp12Add = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), + }); + const Fp12Subtract = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), + }); + const Fp12Multiply = ({ c0, c1 }: Fp12, rhs: Fp12 | bigint) => { + if (typeof rhs === 'bigint') return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; + }; + const Fp12Square = ({ c0, c1 }: Fp12) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub( + Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), + Fp6.mulByNonresidue(ab) + ), + c1: Fp6.add(ab, ab), + }; // AB + AB + }; + function Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; + } + type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + mulByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; + }; + + const Fp12: mod.IField & Fp12Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: notImplemented, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => + Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + + // Bytes utils + fromBytes: (b: Uint8Array): Fp12 => { + if (b.length !== Fp12.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }): Uint8Array => concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t: BigintTwelve): Fp12 => ({ + c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix), + c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power: number) { + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: Fp6.frobeniusMap(lhs.c0, power), + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + mulByFp2: ({ c0, c1 }, rhs: Fp2): Fp12 => ({ + c0: Fp6.mulByFp2(c0, rhs), + c1: Fp6.mulByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }): Fp12 => ({ c0, c1: Fp6.neg(c1) }), + // Sparse multiplication + mul014: ({ c0, c1 }, o0: Fp2, o1: Fp2, o4: Fp2) => { + let t0 = Fp6.mul01(c0, o0, o1); + let t1 = Fp6.mul1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + mul034: ({ c0, c1 }, o0: Fp2, o3: Fp2, o4: Fp2) => { + const a = Fp6.create({ + c0: Fp2.mul(c0.c0, o0), + c1: Fp2.mul(c0.c1, o0), + c2: Fp2.mul(c0.c2, o0), + }); + const b = Fp6.mul01(c1, o3, o4); + const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(b), a), + c1: Fp6.sub(e, Fp6.add(a, b)), + }; + }, + + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: opts.Fp12cyclotomicSquare, + _cyclotomicExp: opts.Fp12cyclotomicExp, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: opts.Fp12finalExponentiate, + }; + + return { Fp, Fp2, Fp6, Fp4Square, Fp12 }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/utils.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/utils.ts new file mode 100644 index 0000000..26a223b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/utils.ts @@ -0,0 +1,368 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +export type Hex = Uint8Array | string; // hex strings are accepted for simplicity +export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { dkLen?: number }): any; // For shake +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; + +export function isBytes(a: unknown): a is Uint8Array { + return ( + a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array') + ); +} + +export function abytes(item: unknown): void { + if (!isBytes(item)) throw new Error('Uint8Array expected'); +} + +export function abool(title: string, value: boolean): void { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} + +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +export function numberToHexUnpadded(num: number | bigint): string { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} + +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${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 } as const; +function asciiToBase16(char: number): number | undefined { + if (char >= asciis._0 && char <= asciis._9) return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10); + return; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) throw new Error('padded 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; + } + return array; +} + +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes: Uint8Array): bigint { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +export function numberToBytesBE(n: number | bigint, len: number): Uint8Array { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n: number | bigint, len: number): Uint8Array { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n: number | bigint): Uint8Array { + 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. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array { + let res: Uint8Array; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". 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} expected ${expectedLength} bytes, got ${len}`); + return res; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + 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; +} + +// Compares 2 u8a-s in kinda constant time +export function equalBytes(a: Uint8Array, b: Uint8Array) { + 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; +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +// Is positive bigint +const isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n; + +export function inRange(n: bigint, min: bigint, max: bigint) { + 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: string, n: bigint, min: bigint, max: bigint) { + // 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 ${typeof n} ${n}`); +} + +// Bit operations + +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n: bigint) { + 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: bigint, pos: number) { + return (n >> BigInt(pos)) & _1n; +} + +/** + * Sets single bit at position. + */ +export function bitSet(n: bigint, pos: number, value: boolean) { + 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: number) => (_2n << BigInt(n - 1)) - _1n; + +// DRBG + +const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut +type Pred = (v: Uint8Array) => T | undefined; +/** + * 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(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg( + hashLen: number, + qByteLen: number, + hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array +): (seed: Uint8Array, predicate: Pred) => T { + 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) + 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: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(u8fr([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: Uint8Array[] = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed: Uint8Array, pred: Pred): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = 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: any) => typeof val === 'bigint', + function: (val: any) => typeof val === 'function', + boolean: (val: any) => typeof val === 'boolean', + string: (val: any) => typeof val === 'string', + stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val: any) => Number.isSafeInteger(val), + array: (val: any) => Array.isArray(val), + field: (val: any, object: any) => (object as any).Fp.isValid(val), + hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +} as const; +type Validator = keyof typeof validatorFns; +type ValMap> = { [K in keyof T]?: Validator }; +// type Record = { [P in K]: T; } + +export function validateObject>( + object: T, + validators: ValMap, + optValidators: ValMap = {} +) { + const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + + const val = object[fieldName as keyof typeof object]; + if (isOptional && val === undefined) return; + if (!checkVal(val, object)) { + throw new Error( + `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}` + ); + } + }; + 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' }); + +/** + * 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: (arg: T, ...args: O) => R) { + const map = new WeakMap(); + return (arg: T, ...args: O): R => { + const val = map.get(arg); + if (val !== undefined) return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/abstract/weierstrass.ts b/src/libMPC/node_modules/@noble/curves/src/abstract/weierstrass.ts new file mode 100644 index 0000000..e72d7cc --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/abstract/weierstrass.ts @@ -0,0 +1,1312 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import { + AffinePoint, + BasicCurve, + Group, + GroupConstructor, + validateBasic, + wNAF, + pippenger, +} from './curve.js'; +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey, ensureBytes, memoized, abool } from './utils.js'; + +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint }; +}; +export type BasicWCurve = BasicCurve & { + // Params: a, b + a: T; + b: T; + + // Optional params + allowedPrivateKeyLengths?: readonly number[]; // for P521 + wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n + endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves + // When a cofactor != 1, there can be an effective methods to: + // 1. Determine whether a point is torsion-free + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + // 2. Clear torsion component + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; + +type Entropy = Hex | boolean; +export type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean }; +export type VerOpts = { lowS?: boolean; prehash?: boolean }; + +function validateSigVerOpts(opts: SignOpts | VerOpts) { + if (opts.lowS !== undefined) abool('lowS', opts.lowS); + if (opts.prehash !== undefined) abool('prehash', opts.prehash); +} + +/** + * ### 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 + */ + +// Instance for 3d XYZ points +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +// Static methods for 3d XYZ points +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; + msm(points: ProjPointType[], scalars: bigint[]): ProjPointType; +} + +export type CurvePointsType = BasicWCurve & { + // Bytes + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; + +function validatePointOpts(curve: CurvePointsType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + a: 'field', + b: 'field', + }, + { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + } + ); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if ( + typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function' + ) { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts } as const); +} + +export type CurvePointsRes = { + CURVE: ReturnType>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; + +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; + +/** + * 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: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag: number, data: string) => { + 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 = ut.numberToHexUnpadded(dataLen); + if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 0b1000_0000) : ''; + return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } { + 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 & 0b1000_0000); // 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 & 0b0111_1111; + 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: bigint) { + const { Err: E } = DER; + if (num < _0n) throw new E('integer: negative integers are not allowed'); + let hex = ut.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 assertion'); + return hex; + }, + decode(data: Uint8Array): bigint { + const { Err: E } = DER; + if (data[0] & 0b1000_0000) throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 0b1000_0000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex: string | Uint8Array): { r: bigint; s: bigint } { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + ut.abytes(data); + 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: { r: bigint; s: bigint }): string { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + 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 weierstrassPoints(opts: CurvePointsType): CurvePointsRes { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = mod.Field(CURVE.n, CURVE.nBitLength); + + const toBytes = + CURVE.toBytes || + ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = + CURVE.fromBytes || + ((bytes: Uint8Array) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x: T): T { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num: bigint): boolean { + return ut.inRange(num, _1n, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key: PrivKey): bigint { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (ut.isBytes(key)) key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num: bigint; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) num = mod.mod(num, N); // disabled by default, enabled for BLS + ut.aInRange('private key', num, _1n, N); // num in range [1..N-1] + return num; + } + + function assertPrjPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ProjectivePoint expected'); + } + + // 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: Point, iz?: T): AffinePoint => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) return { x, 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 ax = Fp.mul(x, iz); + const ay = 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: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p: Point) => { + 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 wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + + /** + * 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 implements ProjPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + + constructor( + readonly px: T, + readonly py: T, + readonly pz: T + ) { + if (px == null || !Fp.isValid(px)) throw new Error('x required'); + if (py == null || !Fp.isValid(py)) throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) throw new Error('z required'); + Object.freeze(this); + } + + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p: AffinePoint): Point { + 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'); + const is0 = (i: T) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + + get x(): T { + return this.toAffine().x; + } + get y(): T { + return this.toAffine().y; + } + + /** + * 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. + */ + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex: Hex): Point { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey: PrivKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + + // Multiscalar Multiplication + static msm(points: Point[], scalars: bigint[]) { + return pippenger(Point, Fn, points, scalars); + } + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + wnaf.setWindowSize(this, windowSize); + } + + // A point on curve is valid if it conforms to equation. + assertValidity(): void { + assertValidMemo(this); + } + + hasEvenY(): boolean { + const { y } = this.toAffine(); + if (Fp.isOdd) return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + + /** + * Compare one point to another. + */ + equals(other: Point): boolean { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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(): Point { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + + // 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 { px: X1, py: Y1, pz: 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: Point): Point { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: 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: Point) { + return this.add(other.negate()); + } + + is0() { + return this.equals(Point.ZERO); + } + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + + /** + * 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 private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc: bigint): Point { + ut.aInRange('scalar', sc, _0n, CURVE.n); + const I = Point.ZERO; + if (sc === _0n) return I; + if (sc === _1n) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, sc); + + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d: Point = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + + /** + * 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: bigint): Point { + const { endo, n: N } = CURVE; + ut.aInRange('scalar', scalar, _1n, N); + let point: Point, fake: Point; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = ( + P: Point, + a: bigint // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + + // 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) + toAffine(iz?: T): AffinePoint { + return toAffineMemo(this, iz); + } + isTorsionFree(): boolean { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) return true; // No subgroups, always torsion-free + if (isTorsionFree) return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor(): Point { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) return this; // Fast-path + if (clearCofactor) return clearCofactor(Point, this) as Point; + return this.multiplyUnsafe(CURVE.h); + } + + toRawBytes(isCompressed = true): Uint8Array { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + + toHex(isCompressed = true): string { + abool('isCompressed', isCompressed); + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point as ProjConstructor, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} + +// Instance +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +// Static methods +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { r: bigint; s: bigint }; + +export type PubKey = Hex | ProjPointType; + +export type CurveType = BasicWCurve & { + hash: CHash; // CHash not FHash because we need outputLen for DRBG + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, + { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + } + ); + return Object.freeze({ lowS: true, ...opts } as const); +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +export function weierstrass(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + + function modN(a: bigint) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a: bigint) { + return mod.invert(a, CURVE_ORDER); + } + + const { + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed: boolean): Uint8Array { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes: Uint8Array) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!ut.inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y: bigint; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes` + ); + } + }, + }); + const numToNByteStr = (num: bigint): string => + ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + + function isBiggerThanHalfOrder(number: bigint) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + + function normalizeS(s: bigint) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to)); + + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature implements SignatureType { + constructor( + readonly r: bigint, + readonly s: bigint, + readonly recovery?: number + ) { + this.assertValidity(); + } + + // pair (bytes of r, bytes of s) + static fromCompact(hex: Hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex: Hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + + assertValidity(): void { + ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N] + ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N] + } + + addRecoveryBit(recovery: number): RecoveredSignature { + return new Signature(this.r, this.s, recovery) as RecoveredSignature; + } + + recoverPublicKey(msgHash: Hex): typeof Point.BASE { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + + // Signatures should be low-s, to prevent malleability. + hasHighS(): boolean { + return isBiggerThanHalfOrder(this.s); + } + + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + type RecoveredSignature = Signature & { recovery: number }; + + const utils = { + isValidPrivateKey(privateKey: PrivKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: (): Uint8Array => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item: PrivKey | PubKey): boolean { + const arr = ut.isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && (item as Hex).length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) return true; + return false; + } + + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array { + if (isProbPub(privateA)) throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + + // 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 = + CURVE.bits2int || + function (bytes: Uint8Array): bigint { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = + CURVE.bits2int_modN || + function (bytes: Uint8Array): bigint { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num: bigint): Uint8Array { + ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = ut.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. + function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) return; + // 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 + const s = modN(ik * modN(m + r * d)); // Not using blinding here + 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 = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false }; + + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. 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: Hex | SignatureLike, + msgHash: Hex, + publicKey: Hex, + opts = defaultVerOpts + ): boolean { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + + let _sig: Signature | undefined = undefined; + let P: ProjPointType; + try { + if (typeof sg === 'string' || ut.isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } catch (error) { + if ((error as Error).message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/** + * 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: mod.IField, Z: T) { + // 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: T, v: T): { isValid: boolean; value: T } => { + 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: T, v: T) => { + 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: mod.IField, + opts: { + A: T; + B: T; + Z: T; + } +) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u: T): { x: T; y: T } => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.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, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.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, opts.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, opts.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) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/bls12-381.ts b/src/libMPC/node_modules/@noble/curves/src/bls12-381.ts new file mode 100644 index 0000000..2de169e --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/bls12-381.ts @@ -0,0 +1,756 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls, CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { + bitGet, + bitLen, + bytesToHex, + bytesToNumberBE, + concatBytes as concatB, + ensureBytes, + Hex, + numberToBytesBE, +} from './abstract/utils.js'; +// Types +import { isogenyMap } from './abstract/hash-to-curve.js'; +import { AffinePoint, mapToCurveSimpleSWU, ProjPointType } from './abstract/weierstrass.js'; +import { tower12, psiFrobenius } from './abstract/tower.js'; +import type { Fp, Fp2, Fp6, Fp12 } from './abstract/tower.js'; + +/* +bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to: +- Construct zk-SNARKs at the 120-bit security +- Efficiently verify N aggregate signatures with 1 pairing and N ec additions: + the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr + +### Summary +1. BLS Relies on Bilinear Pairing (expensive) +2. Private Keys: 32 bytes +3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. + - The signature is a point on the G2 subgroup, which is defined over a finite field + with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +5. The 12 stands for the Embedding degree. + +### Formulas +- `P = pk x G` - public keys +- `S = pk x H(m)` - signing +- `e(P, H(m)) == e(G, S)` - verification using pairings +- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation + +### Compatibility and notes +1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC + Filecoin uses little endian byte arrays for private keys - make sure to reverse byte order. +2. Some projects use G2 for public keys and G1 for signatures. It's called "short signature" +3. Curve security level is about 120 bits as per Barbulescu-Duquesne 2017 + https://hal.science/hal-01534101/file/main.pdf +4. Compatible with specs: +[cfrg-pairing-friendly-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +[cfrg-bls-signature-05](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05), +[RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). +*/ + +// 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); + +/* +Embedding degree (k): 12 +Seed (X): -15132376222941642752 +Fr: (x⁴-x²+1) +Fp: ((x-1)² ⋅ r(x)/3+x) +(E/Fp): Y²=X³+4 +(Eₜ/Fp²): Y² = X³+4(u+1) (M-type twist) +Ate loop size: X + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-1-u +- Fp¹²[w] = Fp⁶/w²-v + + +TODO: BLS & BN Fp/Fr can be constructed from seed. +*/ + +// The BLS parameter x (seed) for BLS12-381. NOTE: it is negative! +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); + +// CURVE FIELDS +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = tower12({ + // Order of Fp + ORDER: BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab' + ), + // Finite extension field over irreducible polynominal. + // Fp(u) / (u² - β) where β = -1 + FP2_NONRESIDUE: [_1n, _1n], + Fp2mulByB: ({ c0, c1 }) => { + const t0 = Fp.mul(c0, _4n); // 4 * c0 + const t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + // Fp12 + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }): Fp12 => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}); + +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); + +// END OF CURVE FIELDS + +// HashToCurve + +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +const isogenyMapG2 = isogenyMap( + Fp2, + [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], + ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))) as [Fp2[], Fp2[], Fp2[], Fp2[]] +); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap( + Fp, + [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]] +); + +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create( + BigInt( + '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d' + ) + ), + B: Fp.create( + BigInt( + '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0' + ) + ), + Z: Fp.create(BigInt(11)), +}); + +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const { G2psi, G2psi2 } = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); // 1/(u+1) + +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +} as const); + +// Encoding utils +// Point on G1 curve: (x, y) + +// Compressed point of infinity +const COMPRESSED_ZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true }); // set compressed & point-at-infinity bits + +function parseMask(bytes: Uint8Array) { + // Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo. + bytes = bytes.slice(); + const mask = bytes[0] & 0b1110_0000; + const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000) + const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000) + const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000) + bytes[0] &= 0b0001_1111; // clear mask (zero first 3 bits) + return { compressed, infinity, sort, value: bytes }; +} + +function setMask( + bytes: Uint8Array, + mask: { compressed?: boolean; infinity?: boolean; sort?: boolean } +) { + if (bytes[0] & 0b1110_0000) throw new Error('setMask: non-empty mask'); + if (mask.compressed) bytes[0] |= 0b1000_0000; + if (mask.infinity) bytes[0] |= 0b0100_0000; + if (mask.sort) bytes[0] |= 0b0010_0000; + return bytes; +} + +function signatureG1ToRawBytes(point: ProjPointType) { + point.assertValidity(); + const isZero = point.equals(bls12_381.G1.ProjectivePoint.ZERO); + const { x, y } = point.toAffine(); + if (isZero) return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort }); +} + +function signatureG2ToRawBytes(point: ProjPointType) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const sort = Boolean((tmp / Fp.ORDER) & _1n); + const z2 = x0; + return concatB( + setMask(numberToBytesBE(x1, len), { sort, compressed: true }), + numberToBytesBE(z2, len) + ); +} + +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381: CurveFn = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt( + '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb' + ), + Gy: BigInt( + '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1' + ), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point): boolean => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt( + '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + + // todo: unroll + const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P + const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P + return u2P.equals(phi); + + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(BLS_X).add(point); // x*P + P + }, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if (value.length === 48 && compressed) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(value); + // Zero + const x = Fp.create(compressedValue & Fp.MASK); + if (infinity) { + if (x !== _0n) throw new Error('G1: non-empty compressed point at infinity'); + return { x: _0n, y: _0n }; + } + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) throw new Error('Invalid compressed G1 point'); + if ((y * _2n) / P !== BigInt(sort)) y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } else if (value.length === 96 && !compressed) { + // Check if the infinity flag is set + const x = bytesToNumberBE(value.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(value.subarray(Fp.BYTES)); + if (infinity) { + if (x !== _0n || y !== _0n) throw new Error('G1: non-empty point at infinity'); + return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + } + return { x: Fp.create(x), y: Fp.create(y) }; + } else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + const sort = Boolean((y * _2n) / P); + return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort }); + } else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + ShortSignature: { + fromHex(hex: Hex): ProjPointType { + const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex, 48)); + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(value); + // Zero + if (infinity) return bls12_381.G1.ProjectivePoint.ZERO; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) throw new Error('Invalid compressed G1 point'); + const aflag = BigInt(sort); + if ((y * _2n) / P !== aflag) y = Fp.neg(y); + const point = bls12_381.G1.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point: ProjPointType) { + return signatureG1ToRawBytes(point); + }, + toHex(point: ProjPointType) { + return bytesToHex(signatureG1ToRawBytes(point)); + }, + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt( + '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5' + ), + Gx: Fp2.fromBigTuple([ + BigInt( + '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8' + ), + BigInt( + '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e' + ), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt( + '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801' + ), + BigInt( + '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be' + ), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt( + '0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551' + ), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P): boolean => { + return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = BLS_X; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + const { compressed, infinity, sort, value } = parseMask(bytes); + if ( + (!compressed && !infinity && sort) || // 00100000 + (!compressed && infinity && sort) || // 01100000 + (sort && infinity && compressed) // 11100000 + ) { + throw new Error('Invalid encoding flag: ' + (bytes[0] & 0b1110_0000)); + } + const L = Fp.BYTES; + const slc = (b: Uint8Array, from: number, to?: number) => bytesToNumberBE(b.slice(from, to)); + if (value.length === 96 && compressed) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + if (infinity) { + // check that all bytes are 0 + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(value, 0, L); + const x_0 = slc(value, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = sort && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } else if (value.length === 192 && !compressed) { + if (infinity) { + if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid uncompressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(value, 0, L); + const x0 = slc(value, L, 2 * L); + const y1 = slc(value, 2 * L, 3 * L); + const y0 = slc(value, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + return concatB( + setMask(numberToBytesBE(x.c1, len), { compressed: true, sort: flag }), + numberToBytesBE(x.c0, len) + ); + } else { + if (isZero) return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB( + numberToBytesBE(x1, len), + numberToBytesBE(x0, len), + numberToBytesBE(y1, len), + numberToBytesBE(y0, len) + ); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex: Hex): ProjPointType { + const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex)); + const P = Fp.ORDER; + const half = value.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(value.slice(0, half)); + const z2 = bytesToNumberBE(value.slice(half)); + // Indicates the infinity point + if (infinity) return bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) throw new Error('Failed to find a square root'); + + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = BigInt(sort); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point: ProjPointType) { + return signatureG2ToRawBytes(point); + }, + toHex(point: ProjPointType) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + xNegative: true, + twistType: 'multiplicative', + }, + htfDefaults, + hash: sha256, + randomBytes, +}); diff --git a/src/libMPC/node_modules/@noble/curves/src/bn254.ts b/src/libMPC/node_modules/@noble/curves/src/bn254.ts new file mode 100644 index 0000000..e172dda --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/bn254.ts @@ -0,0 +1,237 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { getHash } from './_shortw_utils.js'; +import { weierstrass } from './abstract/weierstrass.js'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls, CurveFn } from './abstract/bls.js'; +import { Field } from './abstract/modular.js'; +import { bitGet, bitLen, notImplemented } from './abstract/utils.js'; +import { tower12, psiFrobenius } from './abstract/tower.js'; +// Types +import type { Fp, Fp2, Fp6, Fp12 } from './abstract/tower.js'; +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _6n = BigInt(6); + +/* +bn254, previously known as alt_bn_128, when it had 128-bit security. +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/execution-specs/blob/master/src/ethereum/crypto/alt_bn128.py +- Points are encoded differently in different implementations +*/ + +/* +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +Towers: +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v +*/ +const BN_X = BigInt('4965661367192848881'); +const BN_X_LEN = bitLen(BN_X); +const SIX_X_SQUARED = _6n * BN_X ** _2n; + +// Finite field over r. It's for convenience and is not used in the code below. +const Fr = Field( + BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617') +); +// Fp2.div(Fp2.mul(Fp2.ONE, _3n), Fp2.NONRESIDUE) +const Fp2B = { + c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'), + c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'), +}; + +const { Fp, Fp2, Fp6, Fp4Square, Fp12 } = tower12({ + ORDER: BigInt('21888242871839275222246405745257275088696311157297823662689037894645226208583'), + FP2_NONRESIDUE: [BigInt(9), _1n], + Fp2mulByB: (num) => Fp2.mul(num, Fp2B), + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + Fp12cyclotomicSquare: ({ c0, c1 }): Fp12 => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + Fp12cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BN_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + Fp12finalExponentiate: (num) => { + const powMinusX = (num: Fp12) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X)); + const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num)); + const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0); + const y1 = Fp12._cyclotomicSquare(powMinusX(r)); + const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1); + const y4 = powMinusX(y2); + const y6 = powMinusX(Fp12._cyclotomicSquare(y4)); + const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2)); + const y9 = Fp12.mul(y8, y1); + return Fp12.mul( + Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), + Fp12.mul( + Fp12.frobeniusMap(y8, 2), + Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r)) + ) + ); + }, +}); + +// END OF CURVE FIELDS +const { G2psi, psi } = psiFrobenius(Fp, Fp2, Fp2.NONRESIDUE); + +/* +No hashToCurve for now (and signatures): + +- RFC 9380 doesn't mention bn254 and doesn't provide test vectors +- Overall seems like nobody is using BLS signatures on top of bn254 +- Seems like it can utilize SVDW, which is not implemented yet +*/ +const htfDefaults = Object.freeze({ + // DST: a domain separation tag defined in section 2.2.5 + DST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_', + p: Fp.ORDER, + m: 2, + k: 128, + expand: 'xmd', + hash: sha256, +} as const); + +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings. + */ +export const bn254: CurveFn = bls({ + // Fields + fields: { Fp, Fp2, Fp6, Fp12, Fr }, + G1: { + Fp, + h: BigInt(1), + Gx: BigInt(1), + Gy: BigInt(2), + a: Fp.ZERO, + b: _3n, + htfDefaults: { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: notImplemented, + fromBytes: notImplemented, + toBytes: notImplemented, + ShortSignature: { + fromHex: notImplemented, + toRawBytes: notImplemented, + toHex: notImplemented, + }, + }, + G2: { + Fp: Fp2, + // cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1 + h: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + Gx: Fp2.fromBigTuple([ + BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'), + BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'), + BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'), + ]), + a: Fp2.ZERO, + b: Fp2B, + hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P + mapToCurve: notImplemented, + fromBytes: notImplemented, + toBytes: notImplemented, + Signature: { + fromHex: notImplemented, + toRawBytes: notImplemented, + toHex: notImplemented, + }, + }, + params: { + ateLoopSize: BN_X * _6n + _2n, + r: Fr.ORDER, + xNegative: false, + twistType: 'divisive', + }, + htfDefaults, + hash: sha256, + randomBytes, + + postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => { + const q = psi(Qx, Qy); + ({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1])); + const q2 = psi(q[0], q[1]); + pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1])); + }, +}); + +/** + * bn254 weierstrass curve with ECDSA. + * This is very rare and probably not used anywhere. + * Instead, you should use G1 / G2, defined above. + */ +export const bn254_weierstrass = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp, + n: BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/src/libMPC/node_modules/@noble/curves/src/ed25519.ts b/src/libMPC/node_modules/@noble/curves/src/ed25519.ts new file mode 100644 index 0000000..f7e30ec --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/ed25519.ts @@ -0,0 +1,508 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { AffinePoint, Group } from './abstract/curve.js'; +import { CurveFn, ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { createHasher, expand_message_xmd, htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; + +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ + +const ED25519_P = BigInt( + '57896044618658097711785492504343953926634992332820282019728792003956564819949' +); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt( + '19681161376707505956807079304988542015446066515923890162744021073123829784752' +); + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _5n = BigInt(5), _8n = BigInt(8); + +function ed25519_pow_2_252_3(x: bigint) { + // prettier-ignore + const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} + +// sqrt(u/v) +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} + +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; + +const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))(); + +const ed25519Defaults = /* @__PURE__ */ (() => + ({ + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: _8n, + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, + }) as const)(); + +/** + * ed25519 curve with EdDSA signatures. + */ +export const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))(); + +function ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) { + if (ctx.length > 255) throw new Error('Context is too big'); + return concatBytes( + utf8ToBytes('SigEd25519 no Ed25519 collisions'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); +} + +export const ed25519ctx = /* @__PURE__ */ (() => + twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + }))(); +export const ed25519ph = /* @__PURE__ */ (() => + twistedEdwards( + Object.assign({}, ed25519Defaults, { + domain: ed25519_domain, + prehash: sha512, + }) + ))(); + +export const x25519 = /* @__PURE__ */ (() => + montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x: bigint): bigint => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, _3n, P) * b2, P); + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} + +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart + +const ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1 +const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1) + +// prettier-ignore +function map_to_curve_elligator2_curve25519(u: bigint) { + const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic + const ELL2_J = BigInt(486662); + + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} + +const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u: bigint) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed25519.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]), + { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertRstPoint(other: unknown) { + if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected'); +} + +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt( + '25063068953384623474111414158702152701244531502492656460079210482610430750235' +); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt( + '54469307008909316920995813868745141605393597292927456921205312896311721017578' +); +// 1-d² +const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt( + '1159843021668779879193775521855586647937357759715417654439879720876111806838' +); +// (d-1)² +const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt( + '40440834346308536858101042469323190826248399146238708352240133220865137265952' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_255B = /* @__PURE__ */ BigInt( + '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +); +const bytes255ToNumberLE = (bytes: Uint8Array) => + ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0: bigint): ExtendedPoint { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) s_ = mod(-s_); + if (!Ns_D_is_sq) s = s_; // 7 + if (!Ns_D_is_sq) c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint implements Group { + static BASE: RistPoint; + static ZERO: RistPoint; + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D: bigint; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + equals(other: RistPoint): boolean { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + + add(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + + subtract(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } + + double(): RistPoint { + return new RistPoint(this.ep.double()); + } + + negate(): RistPoint { + return new RistPoint(this.ep.negate()); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); + +// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B +export const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_ristretto255 = hashToRistretto255; // legacy diff --git a/src/libMPC/node_modules/@noble/curves/src/ed448.ts b/src/libMPC/node_modules/@noble/curves/src/ed448.ts new file mode 100644 index 0000000..a714149 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/ed448.ts @@ -0,0 +1,480 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { AffinePoint, Group } from './abstract/curve.js'; +import { ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { createHasher, expand_message_xof, htfBasicOpts } from './abstract/hash-to-curve.js'; +import { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; + +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ + +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439' +); + +// prettier-ignore +const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x: bigint): bigint { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + 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 b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} + +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} + +const Fp = Field(ed448P, 456, true); + +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358' + ), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt( + '181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779' + ), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt( + '224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710' + ), + Gy: BigInt( + '298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660' + ), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length > 255) throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes( + utf8ToBytes('SigEd448'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); + }, + uvRatio, +} as const; + +export const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); + +export const x448 = /* @__PURE__ */ (() => + montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x: bigint): bigint => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} + +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version + +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); + +function map_to_curve_elligator2_curve448(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} + +function map_to_curve_elligator2_edwards448(u: bigint) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed448.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards448(scalars[0]), + { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertDcfPoint(other: unknown) { + if (!(other instanceof DcfPoint)) throw new Error('DecafPoint expected'); +} + +// 1-d +const ONE_MINUS_D = BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = BigInt( + '98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214' +); +// 1 / √(-d) +const INVSQRT_MINUS_D = BigInt( + '315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_448B = BigInt( + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +); +const bytes448ToNumberLE = (bytes: Uint8Array) => + ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Decaf +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 +function calcElligatorDecafMap(r0: bigint): ExtendedPoint { + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + + const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + + let v_prime = v; // 5 + if (!was_square) v_prime = mod(r0 * v); + + let sgn = _1n; // 6 + if (!was_square) sgn = mod(-_1n); + + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) s_abs = mod(-s); + + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed448/ExtendedPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class DcfPoint implements Group { + static BASE: DcfPoint; + static ZERO: DcfPoint; + // Private property to discourage combining ExtendedPoint + DecafPoint + // Always use Decaf encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2 + * @param hex 112-byte output of a hash function + */ + static hashToCurve(hex: Hex): DcfPoint { + hex = ensureBytes('decafHash', hex, 112); + const r1 = bytes448ToNumberLE(hex.slice(0, 56)); + const R1 = calcElligatorDecafMap(r1); + const r2 = bytes448ToNumberLE(hex.slice(56, 112)); + const R2 = calcElligatorDecafMap(r2); + return new DcfPoint(R1.add(R2)); + } + + /** + * Converts decaf-encoded string to decaf point. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2 + * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: Hex): DcfPoint { + hex = ensureBytes('decafHex', hex, 56); + const { d } = ed448.CURVE; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint'; + const s = bytes448ToNumberLE(hex); + + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P)) throw new Error(emsg); + + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) u3 = mod(-u3); + + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + + if (!isValid) throw new Error(emsg); + return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes decaf point to Uint8Array. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2 + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: _y, ez: z, et: t } = this.ep; + const P = ed448.CURVE.Fp.ORDER; + const mod = ed448.CURVE.Fp.create; + + const u1 = mod(mod(x + t) * mod(x - t)); // 1 + const x2 = mod(x * x); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) ratio = mod(-ratio); + + const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4 + + let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5 + if (isNegativeLE(s, P)) s = mod(-s); + + return numberToBytesLE(s, 56); + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2 + equals(other: DcfPoint): boolean { + assertDcfPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed448.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) + return mod(X1 * Y2) === mod(Y1 * X2); + } + + add(other: DcfPoint): DcfPoint { + assertDcfPoint(other); + return new DcfPoint(this.ep.add(other.ep)); + } + + subtract(other: DcfPoint): DcfPoint { + assertDcfPoint(other); + return new DcfPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): DcfPoint { + return new DcfPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): DcfPoint { + return new DcfPoint(this.ep.multiplyUnsafe(scalar)); + } + + double(): DcfPoint { + return new DcfPoint(this.ep.double()); + } + + negate(): DcfPoint { + return new DcfPoint(this.ep.negate()); + } +} + +export const DecafPoint = /* @__PURE__ */ (() => { + // decaf448 base point is ed448 base x 2 + // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699 + if (!DcfPoint.BASE) DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n); + if (!DcfPoint.ZERO) DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO); + return DcfPoint; +})(); + +// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C +export const hashToDecaf448 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256); + const P = DcfPoint.hashToCurve(uniform_bytes); + return P; +}; +export const hash_to_decaf448 = hashToDecaf448; // legacy diff --git a/src/libMPC/node_modules/@noble/curves/src/index.ts b/src/libMPC/node_modules/@noble/curves/src/index.ts new file mode 100644 index 0000000..6afa9aa --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/index.ts @@ -0,0 +1 @@ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/src/libMPC/node_modules/@noble/curves/src/jubjub.ts b/src/libMPC/node_modules/@noble/curves/src/jubjub.ts new file mode 100644 index 0000000..e4c4fac --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/jubjub.ts @@ -0,0 +1,63 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { blake2s } from '@noble/hashes/blake2s'; +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { Field } from './abstract/modular.js'; + +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ + +export const jubjub = /* @__PURE__ */ twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +} as const); + +const GH_FIRST_BLOCK = utf8ToBytes( + '096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0' +); + +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag: Uint8Array, personalization: Uint8Array) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) throw new Error('Point has small order'); + return p; +} + +// No secret data is leaked here at all. +// It operates over public data: +// const G_SPEND = jubjub.findGroupHash(new Uint8Array(), utf8ToBytes('Item_G_')); +export function findGroupHash(m: Uint8Array, personalization: Uint8Array) { + const tag = concatBytes(m, new Uint8Array([0])); + const hashes = []; + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + hashes.push(groupHash(tag, personalization)); + } catch (e) {} + } + if (!hashes.length) throw new Error('findGroupHash tag overflow'); + return hashes[0]; +} diff --git a/src/libMPC/node_modules/@noble/curves/src/p256.ts b/src/libMPC/node_modules/@noble/curves/src/p256.ts new file mode 100644 index 0000000..c0577f5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/p256.ts @@ -0,0 +1,48 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +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'; + +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 + +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); + +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +} as const, sha256); +export const secp256r1 = p256; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/src/libMPC/node_modules/@noble/curves/src/p384.ts b/src/libMPC/node_modules/@noble/curves/src/p384.ts new file mode 100644 index 0000000..856a10b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/p384.ts @@ -0,0 +1,52 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha384 } from '@noble/hashes/sha512'; +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'; + +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); + +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +} as const, sha384); +export const secp384r1 = p384; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp384r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/src/libMPC/node_modules/@noble/curves/src/p521.ts b/src/libMPC/node_modules/@noble/curves/src/p521.ts new file mode 100644 index 0000000..103052b --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/p521.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +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'; + +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); + +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt( + '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00' + ), + Fp, + n: BigInt( + '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409' + ), + Gx: BigInt( + '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66' + ), + Gy: BigInt( + '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650' + ), + h: BigInt(1), +}; + +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +} as const, sha512); +export const secp521r1 = p521; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp521r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/src/libMPC/node_modules/@noble/curves/src/package.json b/src/libMPC/node_modules/@noble/curves/src/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/src/libMPC/node_modules/@noble/curves/src/pasta.ts b/src/libMPC/node_modules/@noble/curves/src/pasta.ts new file mode 100644 index 0000000..13a5653 --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/pasta.ts @@ -0,0 +1,31 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { getHash } from './_shortw_utils.js'; +import { Field, mod } from './abstract/modular.js'; +import { weierstrass } from './abstract/weierstrass.js'; + +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); + +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: Field(p), + n: q, + Gx: mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: Field(q), + n: p, + Gx: mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/src/libMPC/node_modules/@noble/curves/src/secp256k1.ts b/src/libMPC/node_modules/@noble/curves/src/secp256k1.ts new file mode 100644 index 0000000..1bafaeb --- /dev/null +++ b/src/libMPC/node_modules/@noble/curves/src/secp256k1.ts @@ -0,0 +1,286 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { createCurve } from './_shortw_utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { + inRange, + aInRange, + bytesToNumberBE, + concatBytes, + ensureBytes, + numberToBytesBE, +} from './abstract/utils.js'; +import { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js'; + +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b; + +/** + * √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: bigint): bigint { + const P = secp256k1P; + // 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 (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root'); + return root; +} + +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +export const secp256k1 = createCurve( + { + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k: bigint) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + 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 +const _0n = BigInt(0); +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {}; +function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + 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: PointType) => point.toRawBytes(true).slice(1); +const numTo32b = (n: bigint) => numberToBytesBE(n, 32); +const modP = (x: bigint) => mod(x, secp256k1P); +const modN = (x: bigint) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q: PointType, a: bigint, b: bigint) => + Point.BASE.multiplyAndAddUnsafe(Q, a, b); + +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv: PrivKey) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: 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: bigint): PointType { + aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +const num = bytesToNumberBE; +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args: Uint8Array[]): bigint { + return modN(num(taggedHash('BIP0340/challenge', ...args))); +} + +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey: Hex): Uint8Array { + return schnorrGetExtPubKey(privateKey).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: Hex, + privateKey: PrivKey, + auxRand: Hex = randomBytes(32) +): Uint8Array { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(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) + const k_ = modN(num(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + 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(numTo32b(modN(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: Hex, message: Hex, publicKey: Hex): boolean { + 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, secp256k1P)) return false; + const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!inRange(s, _1n, secp256k1N)) return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } catch (error) { + return false; + } +} + +/** + * Schnorr signatures over secp256k1. + */ +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); + +const isoMap = /* @__PURE__ */ (() => + isogenyMap( + Fp, + [ + // 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))) as [bigint[], bigint[], bigint[], bigint[]] + ))(); +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), + }))(); +const htf = /* @__PURE__ */ (() => + createHasher( + secp256k1.ProjectivePoint, + (scalars: bigint[]) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); + }, + { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/src/libMPC/node_modules/@noble/hashes/LICENSE b/src/libMPC/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/README.md b/src/libMPC/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..2284f43 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/README.md @@ -0,0 +1,550 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt & Argon2. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🏎 Fast: hand-optimized for caveats of JS engines +- 🔍 Reliable: chained / sliding window / DoS tests and fuzzing ensure correctness +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, cSHAKE, KangarooTwelve, MarsupilamiFourteen and TurboSHAKE +- 🪶 89KB (17KB gzipped) for everything, 10KB (2.5KB gzipped) for single-hash build + +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support. +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out homepage](https://paulmillr.com/noble/) + for reading resources, documentation and apps built with noble + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +```js +// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size +import { sha256 } from '@noble/hashes/sha2'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha2'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) +``` + +- [Implementations](#implementations) + - [sha2: sha256, sha384, sha512 and others](#sha2-sha256-sha384-sha512-and-others) + - [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak) + - [sha3-addons: cSHAKE, KMAC, K12, M14, TurboSHAKE](#sha3-addons-cshake-kmac-k12-m14-turboshake) + - [ripemd160](#ripemd160) + - [blake2b, blake2s, blake3](#blake2b-blake2s-blake3) + - [sha1: legacy hash](#sha1-legacy-hash) + - [hmac](#hmac) + - [hkdf](#hkdf) + - [pbkdf2](#pbkdf2) + - [scrypt](#scrypt) + - [argon2](#argon2) + - [utils](#utils) + - [All available imports](#all-available-imports) +- [Security](#security) + - [Constant-timeness](#constant-timeness) + - [Memory dumping](#memory-dumping) + - [Supply chain security](#supply-chain-security) + - [Randomness](#randomness) +- [Speed](#speed) +- [Contributing & testing](#contributing--testing) +- [Resources](#resources) +- [License](#license) + +### Implementations + +All hash functions: + +- receive `Uint8Array` and return `Uint8Array` +- may receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support little-endian and big-endian architectures +- can hash up to 4GB per chunk, with any amount of chunks + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +##### sha2: sha256, sha384, sha512 and others + +```typescript +import { sha256, sha384, sha512, sha224, sha512_256, sha512_384 } from '@noble/hashes/sha2'; +// also available as aliases: +// import ... from '@noble/hashes/sha256' +// import ... from '@noble/hashes/sha512' + +// Variant A: +const h1a = sha256('abc'); + +// Variant B: +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +for (let hash of [sha384, sha512, sha224, sha512_256, sha512_384]) { + const res1 = hash('abc'); + const res2 = hash + .create() + .update('def') + .update(Uint8Array.from([1, 2, 3])) + .digest(); +} +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### sha3: FIPS, SHAKE, Keccak + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### sha3-addons: cSHAKE, KMAC, K12, M14, TurboSHAKE + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + turboshake128, + turboshake256, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7t1 = turboshake128('abc'); +const h7t2 = turboshake256('def', { D: 0x05 }); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- [Reduced-round Keccak](https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/): + - 🦘 K12 aka KangarooTwelve + - M14 aka MarsupilamiFourteen + - TurboSHAKE +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### ripemd160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### blake2b, blake2s, blake3 + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { blake3 } from '@noble/hashes/blake3'; + +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### sha1: legacy hash + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### hmac + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha2'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac + .create(sha256, Uint8Array.from([1, 2, 3])) + .update(Uint8Array.from([4, 5, 6])) + .digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### hkdf + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha2'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha2'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### pbkdf2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha2'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### argon2 + +> [!WARNING] +> Experimental: it may be removed at any time. + +Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +##### All available imports + +```js +import { sha256, sha384, sha512, sha224, sha512_256, sha512_384 } from '@noble/hashes/sha2'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, + turboshake128, turboshake256, + kmac128, kmac256, + tuplehash256, parallelhash256, + k12, m14, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## Security + +The library has been independently audited: + +- at version 1.0.0, in Jan 2022, by [cure53](https://cure53.de) + - PDFs: [online](https://cure53.de/pentest-report_hashing-libs.pdf), [offline, in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). + - Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +It is tested against property-based, cross-library and Wycheproof vectors, +and has fuzzing by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +_JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to +achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +### Memory dumping + +The library shares state buffers between hash +function calls. The buffers are zeroed-out after each call. However, if an attacker +can read application memory, you are doomed in any case: + +- At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings +- Input from a file will stay in file buffers +- Input / output will be re-used multiple times in application which means it could stay in memory +- `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory +- There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +### Supply chain security + +- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures. +- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs +- **Rare releasing** is followed to ensure less re-audit need for end-users +- **Dependencies** are minimized and locked-down: + - If your app has 500 dependencies, any dep could get hacked and you'll be downloading + malware with every install. We make sure to use as few dependencies as possible + - We prevent automatic dependency updates by locking-down version ranges. Every update is checked with `npm-diff` +- **Dev Dependencies** are only used if you want to contribute to the repo. They are disabled for end-users: + - scure-base, scure-bip32, scure-bip39, micro-bmark and micro-should are developed by the same author and follow identical security practices + - prettier (linter), fast-check (property-based testing) and typescript are used for code quality, vector generation and ts compilation. The packages are big, which makes it hard to audit their source code thoroughly and fully + +### Randomness + +We're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +In the past, browsers had bugs that made it weak: it may happen again. +Implementing a userspace CSPRNG to get resilient to the weakness +is even worse: there is no reliable userspace source of quality entropy. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. +7. `npm run format` will fix lint issues + +## Resources + +Check out [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/src/libMPC/node_modules/@noble/hashes/_assert.d.ts b/src/libMPC/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..f66656f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,24 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +export declare function isBytes(a: unknown): a is Uint8Array; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(h: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; +//# sourceMappingURL=_assert.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_assert.js b/src/libMPC/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..8740278 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBytes = isBytes; +exports.number = number; +exports.bool = bool; +exports.bytes = bytes; +exports.hash = hash; +exports.exists = exists; +exports.output = output; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`boolean expected, not ${b}`); +} +// copied from utils +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(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}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(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'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +const assert = { number, bool, bytes, hash, exists, output }; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_assert.js.map b/src/libMPC/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..ac2d77a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;AASA,0BAKC;AAiCQ,wBAAM;AAAE,oBAAI;AAAE,sBAAK;AAAE,oBAAI;AAAE,wBAAM;AAAE,wBAAM;AA/ClD,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,EAAE,CAAC,CAAC;AAChG,CAAC;AAED,SAAS,IAAI,CAAC,CAAU;IACtB,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,oBAAoB;AACpB,SAAgB,OAAO,CAAC,CAAU;IAChC,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,CAAC,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,YAAY,CAAC,CAC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,EAAE,MAAM,EAAE,CAAC;AAC7D,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_blake.d.ts b/src/libMPC/node_modules/@noble/hashes/_blake.d.ts new file mode 100644 index 0000000..ddb3f3a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_blake.d.ts @@ -0,0 +1,28 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} +//# sourceMappingURL=_blake.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_blake.js b/src/libMPC/node_modules/@noble/hashes/_blake.js new file mode 100644 index 0000000..1ecb94c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_blake.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.number)(blockLen); + (0, _assert_js_1.number)(outputLen); + (0, _assert_js_1.number)(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + (0, _assert_js_1.exists)(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(buffer32); + this.compress(buffer32, 0, false); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(data32); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(buffer32); + this.compress(buffer32, 0, true); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(buffer32); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = (0, utils_js_1.byteSwapIfBE)(v))); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE = BLAKE; +//# sourceMappingURL=_blake.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_blake.js.map b/src/libMPC/node_modules/@noble/hashes/_blake.js.map new file mode 100644 index 0000000..38b815b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_blake.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake.js","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAuF;AAEvF,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAmB,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC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,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAxGD,sBAwGC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_md.d.ts b/src/libMPC/node_modules/@noble/hashes/_md.d.ts new file mode 100644 index 0000000..1c34636 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_md.d.ts @@ -0,0 +1,36 @@ +import { Hash, Input } from './utils.js'; +/** + * Choice: a ? b : c + */ +export declare const Chi: (a: number, b: number, c: number) => number; +/** + * Majority function, true if any two inputs is true + */ +export declare const Maj: (a: number, b: number, c: number) => number; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +export declare abstract class HashMD> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} +//# sourceMappingURL=_md.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_md.js b/src/libMPC/node_modules/@noble/hashes/_md.js new file mode 100644 index 0000000..6ef2bc7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_md.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HashMD = exports.Maj = exports.Chi = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +/** + * Polyfill for Safari 14 + */ +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 + */ +const Chi = (a, b, c) => (a & b) ^ (~a & c); +exports.Chi = Chi; +/** + * Majority function, true if any two inputs is true + */ +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +exports.Maj = Maj; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + (0, _assert_js_1.exists)(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + 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 = (0, utils_js_1.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) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(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; + this.buffer.subarray(pos).fill(0); + // 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 = (0, utils_js_1.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.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.HashMD = HashMD; +//# sourceMappingURL=_md.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_md.js.map b/src/libMPC/node_modules/@noble/hashes/_md.js.map new file mode 100644 index 0000000..95bf1ec --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_md.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_md.js","sourceRoot":"","sources":["src/_md.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAC9C,yCAA8D;AAE9D;;GA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AU,CAAC,EAAM;QACf,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,EAAO,EAAC;QAC5C,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AArGD,wBAqGC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_u64.d.ts b/src/libMPC/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..6b8c273 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,55 @@ +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; +//# sourceMappingURL=_u64.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_u64.js b/src/libMPC/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..ae296cc --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = void 0; +exports.fromBig = fromBig; +exports.split = split; +exports.add = add; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +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) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; 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); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// 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); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// 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, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/_u64.js.map b/src/libMPC/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..3543a9c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":";;;AA4DE,0BAAO;AAAE,sBAAK;AAKd,kBAAG;AAjEL,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,+EAA+E;AAC/E,SAAS,OAAO,CAAC,CAAS,EAAE,EAAE,GAAG,KAAK;IACpC,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC;IAClF,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;AACpF,CAAC;AAED,SAAS,KAAK,CAAC,GAAa,EAAE,EAAE,GAAG,KAAK;IACtC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CA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G,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/argon2.d.ts b/src/libMPC/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..9d4139c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,17 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +//# sourceMappingURL=argon2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/argon2.js b/src/libMPC/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..945f4b8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = (0, _u64_js_1.add3L)(Al, Bl, Cl); + return { h: (0, _u64_js_1.add3H)(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const A2_BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore + let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore + let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore + let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotr32H)(Dh, Dl), Dl: (0, _u64_js_1.rotr32L)(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrSH)(Bh, Bl, 24), Bl: (0, _u64_js_1.rotrSL)(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotrSH)(Dh, Dl, 16), Dl: (0, _u64_js_1.rotrSL)(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrBH)(Bh, Bl, 63), Bl: (0, _u64_js_1.rotrBL)(Bh, Bl, 63) }); + (A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah); + (A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh); + (A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch); + (A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + A2_BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(m); + (0, _assert_js_1.number)(t); + (0, _assert_js_1.number)(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // 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(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/argon2.js.map b/src/libMPC/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..4991e74 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAqD;AACrD,6CAAuC;AACvC,uCAA2F;AAS3F,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAA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,MAAM,wBAAgB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADjC,QAAA,OAAO,WAC0B;AACvC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2b.d.ts b/src/libMPC/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..fa5b7f9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE, BlakeOpts } from './_blake.js'; +export declare class BLAKE2b extends BLAKE { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +//# sourceMappingURL=blake2b.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2b.js b/src/libMPC/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..269e97c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,193 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = exports.BLAKE2b = void 0; +const _blake_js_1 = require("./_blake.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const B2B_IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} +function G2b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake_js_1.BLAKE { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = B2B_IV[0] | 0; + this.v0h = B2B_IV[1] | 0; + this.v1l = B2B_IV[2] | 0; + this.v1h = B2B_IV[3] | 0; + this.v2l = B2B_IV[4] | 0; + this.v2h = B2B_IV[5] | 0; + this.v3l = B2B_IV[6] | 0; + this.v3h = B2B_IV[7] | 0; + this.v4l = B2B_IV[8] | 0; + this.v4h = B2B_IV[9] | 0; + this.v5l = B2B_IV[10] | 0; + this.v5h = B2B_IV[11] | 0; + this.v6l = B2B_IV[12] | 0; + this.v6h = B2B_IV[13] | 0; + this.v7l = B2B_IV[14] | 0; + this.v7h = B2B_IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= (0, utils_js_1.byteSwapIfBE)(salt[0]); + this.v4h ^= (0, utils_js_1.byteSwapIfBE)(salt[1]); + this.v5l ^= (0, utils_js_1.byteSwapIfBE)(salt[2]); + this.v5h ^= (0, utils_js_1.byteSwapIfBE)(salt[3]); + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= (0, utils_js_1.byteSwapIfBE)(pers[0]); + this.v6h ^= (0, utils_js_1.byteSwapIfBE)(pers[1]); + this.v7l ^= (0, utils_js_1.byteSwapIfBE)(pers[2]); + this.v7h ^= (0, utils_js_1.byteSwapIfBE)(pers[3]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(B2B_IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = _blake_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + BBUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.BLAKE2b = BLAKE2b; +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2b.js.map b/src/libMPC/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..9b618d9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/bl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AI,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;QAChC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAnID,0BAmIC;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2s.d.ts b/src/libMPC/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..29d4b2f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE, BlakeOpts } from './_blake.js'; +export declare const B2S_IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +export declare class BLAKE2s extends BLAKE { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +//# sourceMappingURL=blake2s.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2s.js b/src/libMPC/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..789b070 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.BLAKE2s = exports.B2S_IV = void 0; +exports.compress = compress; +const _blake_js_1 = require("./_blake.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: same as SHA256 +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +exports.B2S_IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends _blake_js_1.BLAKE { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.B2S_IV[0] | 0; + this.v1 = exports.B2S_IV[1] | 0; + this.v2 = exports.B2S_IV[2] | 0; + this.v3 = exports.B2S_IV[3] | 0; + this.v4 = exports.B2S_IV[4] | 0; + this.v5 = exports.B2S_IV[5] | 0; + this.v6 = exports.B2S_IV[6] | 0; + this.v7 = exports.B2S_IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= (0, utils_js_1.byteSwapIfBE)(salt[0]); + this.v5 ^= (0, utils_js_1.byteSwapIfBE)(salt[1]); + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= (0, utils_js_1.byteSwapIfBE)(pers[0]); + this.v7 ^= (0, utils_js_1.byteSwapIfBE)(pers[1]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.B2S_IV[0], exports.B2S_IV[1], exports.B2S_IV[2], exports.B2S_IV[3], l ^ exports.B2S_IV[4], h ^ exports.B2S_IV[5], isLast ? ~exports.B2S_IV[6] : exports.B2S_IV[6], exports.B2S_IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.BLAKE2s = BLAKE2s; +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake2s.js.map b/src/libMPC/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..9d81df0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AA6BA,4BAyBC;AAtDD,2CAAsD;AACtD,uCAAoC;AACpC,yCAAuF;AAEvF,gCAAgC;AAChC,wFAAwF;AACxF,kBAAkB;AACL,QAAA,MAAM,GAAmB,IAAI,WAAW,CAAC;IACpD,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AAEH,0CAA0C;AAC1C,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,C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AE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAxED,0BAwEC;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake3.d.ts b/src/libMPC/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..701b389 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE } from './_blake.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +export declare class BLAKE3 extends BLAKE implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +//# sourceMappingURL=blake3.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake3.js b/src/libMPC/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..607d7f0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,244 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = exports.BLAKE3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake_js_1 = require("./_blake.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake_js_1.BLAKE { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + (0, _assert_js_1.number)(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.IV); + this.flags = flags | 16 /* B3_Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* B3_Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.IV); + this.flags = flags | 64 /* B3_Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = blake2s_js_1.B2S_IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.B2S_IV[0], blake2s_js_1.B2S_IV[1], blake2s_js_1.B2S_IV[2], blake2s_js_1.B2S_IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* B3_Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* B3_Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* B3_Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.chunkOut++)); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.B2S_IV[0], blake2s_js_1.B2S_IV[1], blake2s_js_1.B2S_IV[2], blake2s_js_1.B2S_IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + if (!utils_js_1.isLE) { + (0, utils_js_1.byteSwap32)(buffer32); + (0, utils_js_1.byteSwap32)(out32); + } + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* B3_Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* B3_Flags.PARENT */; + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.buffer32); + this.compress(this.buffer32, 0, true); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* B3_Flags.CHUNK_START */ : 0) | 2 /* B3_Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +exports.BLAKE3 = BLAKE3; +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/blake3.js.map b/src/libMPC/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..abe1edb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAC7D,uCAAoC;AACpC,2CAAoC;AACpC,6CAAgD;AAChD,yCASoB;AAepB,MAAM,KAAK,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE;IAC9C,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,C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AAI,CAAC,MAAM,IAAI,IAAI,CAAC;YACpB,GAAG,IAAI,IAAI,CAAC;QACd,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,CAAC,GAAe;QACrB,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,IAAA,mBAAM,EAAC,KAAK,CAAC,CAAC;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,IAAA,mBAAM,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AA/MD,wBA+MC;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAmB,IAAA,qCAA0B,EAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/crypto.d.ts b/src/libMPC/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..ac181a0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1,2 @@ +export declare const crypto: any; +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/crypto.js b/src/libMPC/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/crypto.js.map b/src/libMPC/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/cryptoNode.d.ts b/src/libMPC/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..98bda7b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1,2 @@ +export declare const crypto: any; +//# sourceMappingURL=cryptoNode.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/cryptoNode.js b/src/libMPC/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..210b8cf --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 +// See utils.ts for details. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc + ? nc.webcrypto + : nc && typeof nc === 'object' && 'randomBytes' in nc + ? nc + : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/cryptoNode.js.map b/src/libMPC/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..c1028e9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,0EAA0E;AAC1E,0DAA0D;AAC1D,4BAA4B;AAC5B,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/eskdf.d.ts b/src/libMPC/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..66721eb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,47 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +export interface ESKDF { + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): Promise; +export {}; +//# sourceMappingURL=eskdf.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/eskdf.js b/src/libMPC/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..6a7671a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scrypt = scrypt; +exports.pbkdf2 = pbkdf2; +exports.deriveMainSeed = deriveMainSeed; +exports.eskdf = eskdf; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/eskdf.js.map b/src/libMPC/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..43a4ede --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;AAeA,wBAEC;AAGD,wBAEC;AAoBD,wCASC;AA0GD,sBAuBC;AApLD,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED,qBAAqB;AACrB,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,kBAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;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gC;QACzF,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;QAC5D,MAAM,GAAG,GAAG,IAAA,cAAI,EAAC,kBAAM,EAAE,IAAK,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,qCAAqC;QACrC,OAAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts new file mode 100644 index 0000000..f66656f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts @@ -0,0 +1,24 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +export declare function isBytes(a: unknown): a is Uint8Array; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(h: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; +//# sourceMappingURL=_assert.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts.map new file mode 100644 index 0000000..19f6194 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_assert.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,QAExB;AAED,iBAAS,IAAI,CAAC,CAAC,EAAE,OAAO,QAEvB;AAGD,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAKnD;AAED,iBAAS,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,QAI7D;AAED,KAAK,IAAI,GAAG;IACV,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAAC;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,GAAG,CAAC;CACb,CAAC;AACF,iBAAS,IAAI,CAAC,CAAC,EAAE,IAAI,QAKpB;AAED,iBAAS,MAAM,CAAC,QAAQ,EAAE,GAAG,EAAE,aAAa,UAAO,QAGlD;AACD,iBAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,QAMtC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErD,QAAA,MAAM,MAAM;;;;;;;CAAgD,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_assert.js b/src/libMPC/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..b6006b2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,42 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`boolean expected, not ${b}`); +} +// copied from utils +export function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(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}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(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'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_assert.js.map b/src/libMPC/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..3596c9e --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,SAAS,MAA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AS;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AACD,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;IAClF,CAAC;AACH,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts new file mode 100644 index 0000000..ddb3f3a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts @@ -0,0 +1,28 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} +//# sourceMappingURL=_blake.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts.map new file mode 100644 index 0000000..ef482c7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_blake.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake.d.ts","sourceRoot":"","sources":["../src/_blake.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,KAAK,EAAgD,MAAM,YAAY,CAAC;AAMvF,eAAO,MAAM,KAAK,YAahB,CAAC;AAEH,MAAM,MAAM,SAAS,GAAG;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,KAAK,CAAC;IACZ,IAAI,CAAC,EAAE,KAAK,CAAC;IACb,eAAe,CAAC,EAAE,KAAK,CAAC;CACzB,CAAC;AAEF,8BAAsB,KAAK,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IAa3D,QAAQ,CAAC,QAAQ,EAAE,MAAM;IAClB,SAAS,EAAE,MAAM;IAb1B,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IACpF,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,QAAQ,EAAE,WAAW,CAAC;IAChC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAK;IAC7B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAK;IAC1B,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;gBAGjB,QAAQ,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACxB,IAAI,EAAE,SAAS,YAAK,EACpB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM;IAejB,MAAM,CAAC,IAAI,EAAE,KAAK;IAuClB,UAAU,CAAC,GAAG,EAAE,UAAU;IAa1B,MAAM;IAON,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;CAYtB"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_blake.js b/src/libMPC/node_modules/@noble/hashes/esm/_blake.js new file mode 100644 index 0000000..e3da803 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_blake.js @@ -0,0 +1,120 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, toBytes, u32, isLE, byteSwap32, byteSwapIfBE } from './utils.js'; +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + if (!isLE) + byteSwap32(buffer32); + this.compress(buffer32, 0, false); + if (!isLE) + byteSwap32(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + if (!isLE) + byteSwap32(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + if (!isLE) + byteSwap32(data32); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + if (!isLE) + byteSwap32(buffer32); + this.compress(buffer32, 0, true); + if (!isLE) + byteSwap32(buffer32); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = byteSwapIfBE(v))); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_blake.js.map b/src/libMPC/node_modules/@noble/hashes/esm/_blake.js.map new file mode 100644 index 0000000..73c73dc --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_blake.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake.js","sourceRoot":"","sources":["../src/_blake.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEvF,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC;IAClD,CAAC,E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C,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7D,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts new file mode 100644 index 0000000..1c34636 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts @@ -0,0 +1,36 @@ +import { Hash, Input } from './utils.js'; +/** + * Choice: a ? b : c + */ +export declare const Chi: (a: number, b: number, c: number) => number; +/** + * Majority function, true if any two inputs is true + */ +export declare const Maj: (a: number, b: number, c: number) => number; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +export declare abstract class HashMD> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} +//# sourceMappingURL=_md.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts.map new file mode 100644 index 0000000..2422450 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_md.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_md.d.ts","sourceRoot":"","sources":["../src/_md.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAc,KAAK,EAAW,MAAM,YAAY,CAAC;AAiB9D;;GAEG;AACH,eAAO,MAAM,GAAG,MAAO,MAAM,KAAK,MAAM,KAAK,MAAM,WAAuB,CAAC;AAE3E;;GAEG;AACH,eAAO,MAAM,GAAG,MAAO,MAAM,KAAK,MAAM,KAAK,MAAM,WAAgC,CAAC;AAEpF;;;GAGG;AACH,8BAAsB,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IAe7D,QAAQ,CAAC,QAAQ,EAAE,MAAM;IAClB,SAAS,EAAE,MAAM;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,IAAI,EAAE,OAAO;IAjBxB,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAC/D,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI;IAErC,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAGjB,QAAQ,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,OAAO;IAMxB,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IAyBzB,UAAU,CAAC,GAAG,EAAE,UAAU;IAkC1B,MAAM;IAON,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;CAWtB"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_md.js b/src/libMPC/node_modules/@noble/hashes/esm/_md.js new file mode 100644 index 0000000..691d84b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_md.js @@ -0,0 +1,128 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +/** + * Polyfill for Safari 14 + */ +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 const Chi = (a, b, c) => (a & b) ^ (~a & c); +/** + * Majority function, true if any two inputs is true + */ +export const Maj = (a, b, c) => (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.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + 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) { + exists(this); + output(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; + this.buffer.subarray(pos).fill(0); + // 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.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_md.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_md.js.map b/src/libMPC/node_modules/@noble/hashes/esm/_md.js.map new file mode 100644 index 0000000..912b473 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_md.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_md.js","sourceRoot":"","sources":["../src/_md.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAAM,YAAY,CAAC;AAE9D;;GAEG;AACH,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/F,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,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,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts new file mode 100644 index 0000000..6b8c273 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts @@ -0,0 +1,55 @@ +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; +//# sourceMappingURL=_u64.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts.map new file mode 100644 index 0000000..7580fea --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_u64.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.d.ts","sourceRoot":"","sources":["../src/_u64.ts"],"names":[],"mappings":"AAIA,iBAAS,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,UAAQ;;;EAGrC;AAED,iBAAS,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,UAAQ,iBAQvC;AAED,QAAA,MAAM,KAAK,MAAO,MAAM,KAAK,MAAM,WAAgD,CAAC;AAEpF,QAAA,MAAM,KAAK,MAAO,MAAM,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AM,MAAM,MAAM;iBAItD,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM;gBAFnE,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM;CAsBxE,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_u64.js b/src/libMPC/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..66cce47 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,62 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +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) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; 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 { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +// 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.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/_u64.js.map b/src/libMPC/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..ecba77f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["../src/_u64.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,+EAA+E;AAC/E,SAAS,OAAO,CAAC,CAAS,EAAE,EAAE,GAAG,KAAK;IACpC,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC;IAClF,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;AACpF,CAAC;AAED,SAAS,KAAK,CAAC,GAAa,EAAE,EAAE,GAAG,KAAK;IACtC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACpC,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACrC,CAAC,EAAE,CAAC,CAAC,CAAC,EAA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ashes/esm/argon2.d.ts new file mode 100644 index 0000000..9d4139c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts @@ -0,0 +1,17 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +//# sourceMappingURL=argon2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts.map new file mode 100644 index 0000000..8035207 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/argon2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAoB,MAAM,YAAY,CAAC;AAkKrD,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,KAAK,CAAC;IACZ,eAAe,CAAC,EAAE,KAAK,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAkMF,eAAO,MAAM,OAAO,aAAc,KAAK,QAAQ,KAAK,QAAQ,SAAS,eACvB,CAAC;AAC/C,eAAO,MAAM,OAAO,aAAc,KAAK,QAAQ,KAAK,QAAQ,SAAS,eACxB,CAAC;AAC9C,eAAO,MAAM,QAAQ,aAAc,KAAK,QAAQ,KAAK,QAAQ,SAAS,eACxB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/argon2.js b/src/libMPC/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..682eb34 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,297 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const A2_BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore + let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore + let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore + let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + (A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah); + (A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh); + (A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch); + (A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + A2_BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // 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(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/argon2.js.map b/src/libMPC/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..4a51e8a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"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,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,wBAAgB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts new file mode 100644 index 0000000..fa5b7f9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE, BlakeOpts } from './_blake.js'; +export declare class BLAKE2b extends BLAKE { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +//# sourceMappingURL=blake2b.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts.map new file mode 100644 index 0000000..046c3e0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.d.ts","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAS,MAAM,aAAa,CAAC;AAgEtD,qBAAa,OAAQ,SAAQ,KAAK,CAAC,OAAO,CAAC;IAEzC,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;gBAEjB,IAAI,GAAE,SAAc;IA0BhC,SAAS,CAAC,GAAG,IAAI;QACf,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAC9D,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;KAC/D;IAKD,SAAS,CAAC,GAAG,CACX,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM;IAmBpD,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAkDpE,OAAO;CAKR;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO;;;;;CAEnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..207b222 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE, SIGMA } from './_blake.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts, byteSwapIfBE } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const B2B_IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} +function G2b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} +export class BLAKE2b extends BLAKE { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = B2B_IV[0] | 0; + this.v0h = B2B_IV[1] | 0; + this.v1l = B2B_IV[2] | 0; + this.v1h = B2B_IV[3] | 0; + this.v2l = B2B_IV[4] | 0; + this.v2h = B2B_IV[5] | 0; + this.v3l = B2B_IV[6] | 0; + this.v3h = B2B_IV[7] | 0; + this.v4l = B2B_IV[8] | 0; + this.v4h = B2B_IV[9] | 0; + this.v5l = B2B_IV[10] | 0; + this.v5h = B2B_IV[11] | 0; + this.v6l = B2B_IV[12] | 0; + this.v6h = B2B_IV[13] | 0; + this.v7l = B2B_IV[14] | 0; + this.v7h = B2B_IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= byteSwapIfBE(salt[0]); + this.v4h ^= byteSwapIfBE(salt[1]); + this.v5l ^= byteSwapIfBE(salt[2]); + this.v5h ^= byteSwapIfBE(salt[3]); + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= byteSwapIfBE(pers[0]); + this.v6h ^= byteSwapIfBE(pers[1]); + this.v7l ^= byteSwapIfBE(pers[2]); + this.v7h ^= byteSwapIfBE(pers[3]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(B2B_IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + BBUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js.map b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..8b51057 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAa,KAAK,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEjF,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IAC7C,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,IAAI,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEjD,0CAA0C;AAC1C,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,E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/src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts new file mode 100644 index 0000000..29d4b2f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE, BlakeOpts } from './_blake.js'; +export declare const B2S_IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +export declare class BLAKE2s extends BLAKE { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +//# sourceMappingURL=blake2s.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts.map new file mode 100644 index 0000000..c092a23 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.d.ts","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EA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EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAWhG,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAkBpE,OAAO;CAKR;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO;;;;;CAEnB,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..d601eeb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,119 @@ +import { BLAKE, SIGMA } from './_blake.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32, byteSwapIfBE } from './utils.js'; +// Initial state: same as SHA256 +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +export const B2S_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +export class BLAKE2s extends BLAKE { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = B2S_IV[0] | 0; + this.v1 = B2S_IV[1] | 0; + this.v2 = B2S_IV[2] | 0; + this.v3 = B2S_IV[3] | 0; + this.v4 = B2S_IV[4] | 0; + this.v5 = B2S_IV[5] | 0; + this.v6 = B2S_IV[6] | 0; + this.v7 = B2S_IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= byteSwapIfBE(salt[0]); + this.v5 ^= byteSwapIfBE(salt[1]); + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= byteSwapIfBE(pers[0]); + this.v7 ^= byteSwapIfBE(pers[1]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js.map b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..ddd4acd --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAa,KAAK,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEvF,gCAAgC;AAChC,wFAAwF;AACxF,kBAAkB;AAClB,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACpD,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AAEH,0CAA0C;AAC1C,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAChE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC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,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts new file mode 100644 index 0000000..701b389 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE } from './_blake.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +export declare class BLAKE3 extends BLAKE implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +//# sourceMappingURL=blake3.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts.map new file mode 100644 index 0000000..8eced0b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake3.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC,OAAO,EACL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/esm/blake3.js b/src/libMPC/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..3577963 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,240 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE } from './_blake.js'; +import { compress, B2S_IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js'; +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +export class BLAKE3 extends BLAKE { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + if (!isLE) + byteSwap32(this.IV); + this.flags = flags | 16 /* B3_Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* B3_Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + if (!isLE) + byteSwap32(this.IV); + this.flags = flags | 64 /* B3_Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = B2S_IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* B3_Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* B3_Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* B3_Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + if (!isLE) + byteSwap32(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + if (!isLE) { + byteSwap32(buffer32); + byteSwap32(out32); + } + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* B3_Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* B3_Flags.PARENT */; + if (!isLE) + byteSwap32(this.buffer32); + this.compress(this.buffer32, 0, true); + if (!isLE) + byteSwap32(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* B3_Flags.CHUNK_START */ : 0) | 2 /* B3_Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/blake3.js.map b/src/libMPC/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..c82019a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAEL,EAAE,EACF,GAAG,EACH,OAAO,EAEP,0BAA0B,EAC1B,IAAI,EACJ,UAAU,GACX,MAAM,YAAY,CAAC;AAepB,MAAM,KAAK,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE;IAC9C,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,IA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CAAC;IACD,UAAU,CAAC,GAAe;QACxB,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts new file mode 100644 index 0000000..ac181a0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts @@ -0,0 +1,2 @@ +export declare const crypto: any; +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts.map new file mode 100644 index 0000000..d31325e --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/crypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,MAAM,KACuE,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/crypto.js b/src/libMPC/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/crypto.js.map b/src/libMPC/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts new file mode 100644 index 0000000..98bda7b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts @@ -0,0 +1,2 @@ +export declare const crypto: any; +//# sourceMappingURL=cryptoNode.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map new file mode 100644 index 0000000..2e2f3cf --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,MAAM,KAKF,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..7dd9476 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,11 @@ +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 +// See utils.ts for details. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc + ? nc.webcrypto + : nc && typeof nc === 'object' && 'randomBytes' in nc + ? nc + : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js.map b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..2bca33d --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,0DAA0D;AAC1D,4BAA4B;AAC5B,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts new file mode 100644 index 0000000..66721eb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts @@ -0,0 +1,47 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +export interface ESKDF { + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): Promise; +export {}; +//# sourceMappingURL=eskdf.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts.map new file mode 100644 index 0000000..9236618 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.d.ts","sourceRoot":"","sources":["../src/eskdf.ts"],"names":[],"mappings":"AAeA,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAEjE;AAGD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAEjE;AAiBD;;GAEG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,UAAU,CAS7E;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AA+BjC,KAAK,UAAU,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AACxC,KAAK,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AACnC,KAAK,OAAO,GAAG,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC;AAwChD,MAAM,WAAW,KAAK;IACpB;;;;;;;;OAQG;IACH,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC;IAC1F;;OAEG;IACH,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;GASG;AACH,wBAAsB,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAuB9E"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js.map b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..1a7c815 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["../src/eskdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,MAAM,UAAU,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,OAAO,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED,qBAAqB;AACrB,MAAM,UAAU,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,OAAO,CAAC,MAA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AAG,WAAW,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,gCAAgC;QACzF,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;QAC5D,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,IAAK,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,qCAAqC;QACrC,OAAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts new file mode 100644 index 0000000..f2ff770 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts @@ -0,0 +1,27 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; +//# sourceMappingURL=hkdf.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts.map new file mode 100644 index 0000000..e5b6be0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.d.ts","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,KAAK,EAAW,MAAM,YAAY,CAAC;AAMnD;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,cAO5D;AAMD;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,GAAE,MAAW,cA4BhF;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,IAAI,SACT,KAAK,OACN,KAAK,QACJ,KAAK,GAAG,SAAS,QACjB,KAAK,GAAG,SAAS,UACf,MAAM,eACyC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..8fbdac8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js.map b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..f8fd588 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO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C7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts new file mode 100644 index 0000000..5a9f896 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts @@ -0,0 +1,30 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * 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 declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; +//# sourceMappingURL=hmac.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts.map new file mode 100644 index 0000000..f6b4aa6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hmac.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAW,MAAM,YAAY,CAAC;AAEzD,qBAAa,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACxD,KAAK,EAAE,CAAC,CAAC;IACT,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;gBAEd,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK;IAsBpC,MAAM,CAAC,GAAG,EAAE,KAAK;IAKjB,UAAU,CAAC,GAAG,EAAE,UAAU;IAS1B,MAAM;IAKN,UAAU,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAajC,OAAO;CAKR;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,IAAI;WAAU,KAAK,OAAO,KAAK,WAAW,KAAK,GAAG,UAAU;iBAEpD,KAAK,OAAO,KAAK;CADa,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hmac.js b/src/libMPC/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..02f6975 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,81 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assertHash(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); + pad.fill(0); + } + update(buf) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assertExists(this); + assertBytes(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; + } + 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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/hmac.js.map b/src/libMPC/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..6a8bb0b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,IAAI,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,kBAAkB;AAClB,MAAM,OAAO,IAAwB,SAAQ,IAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,UAAU,CAAC,IAAI,CAAC,CAAC;QACjB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,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AAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACpD,IAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts.map new file mode 100644 index 0000000..535b86d --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/index.js b/src/libMPC/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..d02dc7a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/index.js.map b/src/libMPC/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..d17f53a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/package.json b/src/libMPC/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..f42e46b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,10 @@ +{ + "type": "module", + "sideEffects": false, + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts new file mode 100644 index 0000000..1fb1b27 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts @@ -0,0 +1,16 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * 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 + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; +//# sourceMappingURL=pbkdf2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map new file mode 100644 index 0000000..2556fc4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.d.ts","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAEA,OAAO,EAAQ,KAAK,EAAE,KAAK,EAA6C,MAAM,YAAY,CAAC;AAG3F,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAkCF;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,cAsBhF;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,uBAsB3F"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..3f0c11f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_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(); + u.fill(0); + 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 + */ +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); +} +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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js.map b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..989dcbb --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAsB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChB,YAAY,CAAC,KAAK,CAAC,CAAC;IACpB,YAAY,CAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAA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IACL,CAAC;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts new file mode 100644 index 0000000..1320a14 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts @@ -0,0 +1,25 @@ +import { HashMD } from './_md.js'; +export declare class RIPEMD160 extends HashMD { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=ripemd160.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts.map new file mode 100644 index 0000000..bf78e18 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.d.ts","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAqClC,qBAAa,SAAU,SAAQ,MAAM,CAAC,SAAS,CAAC;IAC9C,OAAO,CAAC,EAAE,CAAkB;IAC5B,OAAO,CAAC,EAAE,CAAkB;IAC5B,OAAO,CAAC,EAAE,CAAkB;IAC5B,OAAO,CAAC,EAAE,CAAkB;IAC5B,OAAO,CAAC,EAAE,CAAkB;;IAK5B,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAIzD,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAOxE,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAmCvD,SAAS,CAAC,UAAU;IAGpB,OAAO;CAKR;AAED;;;GAGG;AACH,eAAO,MAAM,SAAS;;;;;CAAyD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..c8e7100 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,102 @@ +import { HashMD } from './_md.js'; +import { rotl, wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__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) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__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) + R_BUF[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 = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[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 + f(rGroup, br, cr, dr) + R_BUF[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() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js.map b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..343c7c0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC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,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts new file mode 100644 index 0000000..68368e6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts @@ -0,0 +1,30 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * 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 + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; +//# sourceMappingURL=scrypt.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts.map new file mode 100644 index 0000000..009c4c2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.d.ts","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAGA,OAAO,EAA8B,KAAK,EAAyB,MAAM,YAAY,CAAC;AAyEtF,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAqFF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,cA0BpE;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,uBA2B/E"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..b31a7da --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,226 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { rotl, asyncLoop, checkOpts, u32, isLE, byteSwap32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// 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; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(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 + if (N <= 1 || (N & (N - 1)) !== 0 || N > 2 ** 32) { + throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 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 > (2 ** 32 - 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: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (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 }); + B.fill(0); + V.fill(0); + tmp.fill(0); + 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 + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + if (!isLE) + byteSwap32(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(); + } + } + if (!isLE) + byteSwap32(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + if (!isLE) + byteSwap32(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(); + }); + } + if (!isLE) + byteSwap32(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js.map b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..305f4c0 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAS,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEtF,sBAAsB;AAEtB,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,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AAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,IAAI;QAAE,UAAU,CAAC,GAAG,CAAC,CAAC;IAC3B,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts new file mode 100644 index 0000000..f210c5c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts @@ -0,0 +1,26 @@ +import { HashMD } from './_md.js'; +export declare class SHA1 extends HashMD { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha1.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts.map new file mode 100644 index 0000000..a2bcda2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.d.ts","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,UAAU,CAAC;AAa5C,qBAAa,IAAK,SAAQ,MAAM,CAAC,IAAI,CAAC;IACpC,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;;IAK3B,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAIzD,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM;IAOnE,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAoCvD,SAAS,CAAC,UAAU;IAGpB,OAAO;CAIR;AAED;;;;GAIG;AACH,eAAO,MAAM,IAAI;;;;;CAAoD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha1.js b/src/libMPC/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..8975407 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,85 @@ +import { HashMD, Chi, Maj } from './_md.js'; +import { rotl, wrapConstructor } from './utils.js'; +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +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() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha1.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..4ca21c2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,IA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M,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts new file mode 100644 index 0000000..6052a2a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts @@ -0,0 +1,3 @@ +export { sha256, sha224 } from './sha256.js'; +export { sha512, sha512_224, sha512_256, sha384 } from './sha512.js'; +//# sourceMappingURL=sha2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts.map new file mode 100644 index 0000000..dc32e7a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.d.ts","sourceRoot":"","sources":["../src/sha2.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha2.js b/src/libMPC/node_modules/@noble/hashes/esm/sha2.js new file mode 100644 index 0000000..780eb18 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha2.js @@ -0,0 +1,4 @@ +// Usually you either use sha256, or sha512. We re-export them as sha2 for naming consistency. +export { sha256, sha224 } from './sha256.js'; +export { sha512, sha512_224, sha512_256, sha384 } from './sha512.js'; +//# sourceMappingURL=sha2.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha2.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha2.js.map new file mode 100644 index 0000000..b77fde8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.js","sourceRoot":"","sources":["../src/sha2.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts new file mode 100644 index 0000000..b31a842 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts @@ -0,0 +1,37 @@ +import { HashMD } from './_md.js'; +export declare class SHA256 extends HashMD { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +/** + * SHA2-224 hash function + */ +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha256.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts.map new file mode 100644 index 0000000..2969d86 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.d.ts","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,UAAU,CAAC;AA8B5C,qBAAa,MAAO,SAAQ,MAAM,CAAC,MAAM,CAAC;IAGxC,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;IACrB,CAAC,SAAoB;;IAKrB,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM;IAWxF,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAqCvD,SAAS,CAAC,UAAU;IAGpB,OAAO;CAIR;AAiBD;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;CAAsD,CAAC;AAC1E;;GAEG;AACH,eAAO,MAAM,MAAM;;;;;CAAsD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha256.js b/src/libMPC/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..91dbe12 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,126 @@ +import { HashMD, Chi, Maj } from './_md.js'; +import { rotr, wrapConstructor } from './utils.js'; +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 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 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +export class SHA256 extends HashMD { + constructor() { + super(64, 32, 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() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha256.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..d785c23 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,gEAAgE;AAChE,0DAA0D;AAE1D,mBAAmB;AACnB,yFAAyF;AACzF,kBAAkB;AAClB,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IAC/C,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU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AAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts new file mode 100644 index 0000000..151cdf2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts @@ -0,0 +1,154 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): HashXOF; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): HashXOF; +}; +export declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +export declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type TurboshakeOpts = ShakeOpts & { + D?: number; +}; +export declare const turboshake128: { + (msg: Input, opts?: TurboshakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: TurboshakeOpts): HashXOF>; +}; +export declare const turboshake256: { + (msg: Input, opts?: TurboshakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: TurboshakeOpts): HashXOF>; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +export declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(_out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; +//# sourceMappingURL=sha3-addons.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map new file mode 100644 index 0000000..ace68ec --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.d.ts","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EAIL,IAAI,EACJ,OAAO,EAER,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAyB9C,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG;IAAE,eAAe,CAAC,EAAE,KAAK,CAAC;IAAC,MAAM,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAyBjF,eAAO,MAAM,SAAS;;;;;CAA0D,CAAC;AACjF,eAAO,MAAM,SAAS;;;;;CAA0D,CAAC;AAEjF,qBAAa,IAAK,SAAQ,MAAO,YAAW,OAAO,CAAC,IAAI,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line at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..533cfaf --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,356 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32, wrapXOFConstructorWithOpts, } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +export class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +export class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +export class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +const genTurboshake = (blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => { + const D = opts.D === undefined ? 0x1f : opts.D; + // Section 2.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/ + if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f) + throw new Error(`turboshake: wrong domain separation byte: ${D}, should be 0x01..0x7f`); + return new Keccak(blockLen, D, opts.dkLen === undefined ? outputLen : opts.dkLen, true, 12); +}); +export const turboshake128 = /* @__PURE__ */ genTurboshake(168, 256 / 8); +export const turboshake256 = /* @__PURE__ */ genTurboshake(136, 512 / 8); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +export class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +export class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..257310e --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAEL,OAAO,EACP,uBAAuB,EACvB,GAAG,EAGH,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,MAAM,EAAa,MAAM,WAAW,CAAC;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,SAAS,CAAC,IAAe,EAAE,SAAiB;IACnD,OAAO,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SA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AAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts new file mode 100644 index 0000000..82b88a8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts @@ -0,0 +1,98 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +//# sourceMappingURL=sha3.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts.map new file mode 100644 index 0000000..18faedf --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.d.ts","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,IAAI,EAEJ,KAAK,EAIL,OAAO,EAGR,MAAM,YAAY,CAAC;AAoCpB,wBAAgB,OAAO,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,GAAE,MAAW,QAyC1D;AAED,qBAAa,MAAO,SAAQ,IAAI,CAAC,MAAM,CAAE,YAAW,OAAO,CAAC,MAAM,CAAC;IASxD,QAAQ,EAAE,MAAM;IAChB,MAAM,EAAE,MAAM;IACd,SAAS,EAAE,MAAM;IAC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;;;;CAA+C,CAAC;AACrE,eAAO,MAAM,QAAQ;;;;;CAA+C,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3.js b/src/libMPC/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..4809ba7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,214 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js'; +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha3.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..e73a11c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EACL,IAAI,EACJ,GAAG,EAEH,OAAO,EACP,eAAe,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AE,EAAE,CACvE,0BAA0B,CACxB,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAEJ,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrE,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts new file mode 100644 index 0000000..2282d2b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts @@ -0,0 +1,124 @@ +import { HashMD } from './_md.js'; +export declare class SHA512 extends HashMD { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare class SHA512_224 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare class SHA512_256 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare class SHA384 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha512.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts.map new file mode 100644 index 0000000..0a0b9fd --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha512.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.d.ts","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAgClC,qBAAa,MAAO,SAAQ,MAAM,CAAC,MAAM,CAAC;IAKxC,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB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;;CAMrB;AAED,qBAAa,UAAW,SAAQ,MAAM;IAEpC,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;;CAMrB;AAED,qBAAa,MAAO,SAAQ,MAAM;IAEhC,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;IACpB,EAAE,SAAkB;;CAMrB;AAED,eAAO,MAAM,MAAM;;;;;CAAsD,CAAC;AAC1E,eAAO,MAAM,UAAU;;;;;CAA0D,CAAC;AAClF,eAAO,MAAM,UAAU;;;;;CAA0D,CAAC;AAClF,eAAO,MAAM,MAAM;;;;;CAAsD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha512.js b/src/libMPC/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..6ea9be1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { HashMD } from './_md.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__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))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 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() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +export class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +export class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +export class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/sha512.js.map b/src/libMPC/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..7bc2e75 --- /dev/null +++ b/src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E,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts b/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts new file mode 100644 index 0000000..21254c4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts @@ -0,0 +1,96 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export declare function isBytes(a: unknown): a is Uint8Array; +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const rotl: (word: number, shift: number) => number; +export declare const isLE: boolean; +export declare const byteSwap: (word: number) => number; +export declare const byteSwapIfBE: (n: number) => number; +export declare function byteSwap32(arr: Uint32Array): void; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * 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 declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts.map b/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts.map new file mode 100644 index 0000000..8cc9ce2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAYtE,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAKnD;AAGD,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,iBAAiB,GAAG,UAAU,GACjE,WAAW,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,CAAC;AAGtD,eAAO,MAAM,EAAE,QAAS,UAAU,eAA+D,CAAC;AAClG,eAAO,MAAM,GAAG,QAAS,UAAU,gBAC0C,CAAC;AAG9E,eAAO,MAAM,UAAU,QAAS,UAAU,aACgB,CAAC;AAG3D,eAAO,MAAM,IAAI,SAAU,MAAM,SAAS,MAAM,WAA8C,CAAC;AAE/F,eAAO,MAAM,IAAI,SAAU,MAAM,SAAS,MAAM,WACG,CAAC;AAEpD,eAAO,MAAM,IAAI,SAAmE,CAAC;AAErF,eAAO,MAAM,QAAQ,SAAU,MAAM,WAIb,CAAC;AAEzB,eAAO,MAAM,YAAY,MAAc,MAAM,WAAmC,CAAC;AAGjF,wBAAgB,UAAU,CAAC,GAAG,EAAE,WAAW,QAI1C;AAMD;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQpD;AAWD;;GAEG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAgBlD;AAKD,eAAO,MAAM,QAAQ,qBAAiB,CAAC;AAGvC,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,iBAUnF;AAMD;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAG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AC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;UACpD,KAAK,GAAG,UAAU;;;;EAMvC;AAED,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,EACzE,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;UAEX,KAAK,SAAS,CAAC,GAAG,UAAU;;;iBAI1B,CAAC;EAExB;AAED,wBAAgB,0BAA0B,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,EAC/E,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC;UAEd,KAAK,SAAS,CAAC,GAAG,UAAU;;;iBAI1B,CAAC;EAExB;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CASxD"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/utils.js b/src/libMPC/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..a6c6b9a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,191 @@ +/*! 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'; +import { bytes as abytes } from './_assert.js'; +// export { isBytes } from './_assert.js'; +// We can't reuse isBytes from _assert, because somehow this causes huge perf issues +export function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +export const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +export const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// Conditionally byte swap if on a big-endian platform +export const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n); +// In place byte swap for Uint32Array +export function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + abytes(bytes); + // 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(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @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); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded 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; + } + 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; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * 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; +} +/** + * 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; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +const toStr = {}.toString; +export function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(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 wrapConstructorWithOpts(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 wrapXOFConstructorWithOpts(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; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +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 crypto.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/esm/utils.js.map b/src/libMPC/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..7220f4f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,2EAA2E;AAC3E,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OAAO,MAAM,CAAC,WAAW,KAAK,UAAU,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;IACzC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hkdf.d.ts b/src/libMPC/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..f2ff770 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,27 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; +//# sourceMappingURL=hkdf.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hkdf.js b/src/libMPC/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..1a3a82b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = void 0; +exports.extract = extract; +exports.expand = expand; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + (0, _assert_js_1.hash)(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + (0, _assert_js_1.hash)(hash); + (0, _assert_js_1.number)(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hkdf.js.map b/src/libMPC/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..58b39d2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":";;;AAeA,0BAOC;AAYD,wBA4BC;AA9DD,6CAA0E;AAC1E,yCAAmD;AACnD,uCAAiC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,SAAgB,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAA,cAAI,EAAC,IAAI,EAAE,IAAA,kBAAO,EAAC,IAAI,CAAC,EAAE,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,mCAAmC;AACnC,MAAM,YAAY,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzD,MAAM,YAAY,GAAG,eAAe,CAAC,IAAI,UAAU,EAAE,CAAC;AAEtD;;;;;GAKG;AACH,SAAgB,MAAM,CAAC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B,CAAC;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACI,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAN7C,QAAA,IAAI,QAMyC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hmac.d.ts b/src/libMPC/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..5a9f896 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,30 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * 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 declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; +//# sourceMappingURL=hmac.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hmac.js b/src/libMPC/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..74f1f48 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.hash)(hash); + const key = (0, utils_js_1.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); + pad.fill(0); + } + update(buf) { + (0, _assert_js_1.exists)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.bytes)(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; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * 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'); + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/hmac.js.map b/src/libMPC/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..3612e23 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":";;;AAAA,6CAAgG;AAChG,yCAAyD;AACzD,kBAAkB;AAClB,MAAa,IAAwB,SAAQ,eAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;QACjB,MAAM,GAAG,GAAG,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CA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,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/index.d.ts b/src/libMPC/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/index.js b/src/libMPC/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..da92182 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/index.js.map b/src/libMPC/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b6e5db7 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/package.json b/src/libMPC/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..24ead5f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/package.json @@ -0,0 +1,158 @@ +{ + "name": "@noble/hashes", + "version": "1.5.0", + "description": "Audited & minimal 0-dependency JS implementation of SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF & Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/hashes.js noble; node benchmark/kdf.js noble", + "bench:all": "node benchmark/hashes.js; node benchmark/kdf.js", + "bench:install": "npm pack && mv *.tgz benchmark/noble-hashes.tgz && cd benchmark && npm install && cd ..", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:clean": "rm -f *.{js,d.ts,js.map,d.ts.map} esm/*.{js,js.map,d.ts.map}", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "devDependencies": { + "@paulmillr/jsbt": "0.2.1", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "3.3.2", + "typescript": "5.5.2" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "exports": { + ".": { + "import": "./esm/index.js", + "require": "./index.js" + }, + "./crypto": { + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "import": "./esm/_assert.js", + "require": "./_assert.js" + }, + "./_md": { + "import": "./esm/_md.js", + "require": "./_md.js" + }, + "./argon2": { + "import": "./esm/argon2.js", + "require": "./argon2.js" + }, + "./blake2b": { + "import": "./esm/blake2b.js", + "require": "./blake2b.js" + }, + "./blake2s": { + "import": "./esm/blake2s.js", + "require": "./blake2s.js" + }, + "./blake3": { + "import": "./esm/blake3.js", + "require": "./blake3.js" + }, + "./eskdf": { + "import": "./esm/eskdf.js", + "require": "./eskdf.js" + }, + "./hkdf": { + "import": "./esm/hkdf.js", + "require": "./hkdf.js" + }, + "./hmac": { + "import": "./esm/hmac.js", + "require": "./hmac.js" + }, + "./pbkdf2": { + "import": "./esm/pbkdf2.js", + "require": "./pbkdf2.js" + }, + "./ripemd160": { + "import": "./esm/ripemd160.js", + "require": "./ripemd160.js" + }, + "./scrypt": { + "import": "./esm/scrypt.js", + "require": "./scrypt.js" + }, + "./sha1": { + "import": "./esm/sha1.js", + "require": "./sha1.js" + }, + "./sha2": { + "import": "./esm/sha2.js", + "require": "./sha2.js" + }, + "./sha3-addons": { + "import": "./esm/sha3-addons.js", + "require": "./sha3-addons.js" + }, + "./sha3": { + "import": "./esm/sha3.js", + "require": "./sha3.js" + }, + "./sha256": { + "import": "./esm/sha256.js", + "require": "./sha256.js" + }, + "./sha512": { + "import": "./esm/sha512.js", + "require": "./sha512.js" + }, + "./utils": { + "import": "./esm/utils.js", + "require": "./utils.js" + } + }, + "sideEffects": false, + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/src/libMPC/node_modules/@noble/hashes/pbkdf2.d.ts b/src/libMPC/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..1fb1b27 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,16 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * 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 + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; +//# sourceMappingURL=pbkdf2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/pbkdf2.js b/src/libMPC/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..40b919a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2 = pbkdf2; +exports.pbkdf2Async = pbkdf2Async; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + (0, _assert_js_1.hash)(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + (0, _assert_js_1.number)(c); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.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(); + u.fill(0); + 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 + */ +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 = (0, utils_js_1.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); +} +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 = (0, utils_js_1.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 (0, utils_js_1.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 \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/pbkdf2.js.map b/src/libMPC/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..c2da67a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;AAkDA,wBAsBC;AAED,kCAsBC;AAhGD,6CAA0E;AAC1E,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,IAAA,mBAAY,EAAC,CAAC,CAAC,CAAC;IAChB,IAAA,mBAAY,EAAC,KAAK,CAAC,CAAC;IACpB,IAAA,mBAAY,EAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM,GAAG,GAAG,cAAI,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC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/libMPC/node_modules/@noble/hashes/ripemd160.d.ts b/src/libMPC/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..1320a14 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,25 @@ +import { HashMD } from './_md.js'; +export declare class RIPEMD160 extends HashMD { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=ripemd160.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/ripemd160.js b/src/libMPC/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..244744e --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _md_js_1 = require("./_md.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__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) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends _md_js_1.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) + R_BUF[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 = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = ((0, utils_js_1.rotl)(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = (0, utils_js_1.rotl)(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = ((0, utils_js_1.rotl)(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = (0, utils_js_1.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() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/ripemd160.js.map b/src/libMPC/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..f8ee722 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.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,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAhED,8BAgEC;AAED;;;GAGG;AACU,QAAA,SAAS,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/scrypt.d.ts b/src/libMPC/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..68368e6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,30 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * 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 + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; +//# sourceMappingURL=scrypt.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/scrypt.js b/src/libMPC/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..4571890 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,230 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scrypt = scrypt; +exports.scryptAsync = scryptAsync; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// 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 ^= (0, utils_js_1.rotl)(x00 + x12 | 0, 7); + x08 ^= (0, utils_js_1.rotl)(x04 + x00 | 0, 9); + x12 ^= (0, utils_js_1.rotl)(x08 + x04 | 0, 13); + x00 ^= (0, utils_js_1.rotl)(x12 + x08 | 0, 18); + x09 ^= (0, utils_js_1.rotl)(x05 + x01 | 0, 7); + x13 ^= (0, utils_js_1.rotl)(x09 + x05 | 0, 9); + x01 ^= (0, utils_js_1.rotl)(x13 + x09 | 0, 13); + x05 ^= (0, utils_js_1.rotl)(x01 + x13 | 0, 18); + x14 ^= (0, utils_js_1.rotl)(x10 + x06 | 0, 7); + x02 ^= (0, utils_js_1.rotl)(x14 + x10 | 0, 9); + x06 ^= (0, utils_js_1.rotl)(x02 + x14 | 0, 13); + x10 ^= (0, utils_js_1.rotl)(x06 + x02 | 0, 18); + x03 ^= (0, utils_js_1.rotl)(x15 + x11 | 0, 7); + x07 ^= (0, utils_js_1.rotl)(x03 + x15 | 0, 9); + x11 ^= (0, utils_js_1.rotl)(x07 + x03 | 0, 13); + x15 ^= (0, utils_js_1.rotl)(x11 + x07 | 0, 18); + x01 ^= (0, utils_js_1.rotl)(x00 + x03 | 0, 7); + x02 ^= (0, utils_js_1.rotl)(x01 + x00 | 0, 9); + x03 ^= (0, utils_js_1.rotl)(x02 + x01 | 0, 13); + x00 ^= (0, utils_js_1.rotl)(x03 + x02 | 0, 18); + x06 ^= (0, utils_js_1.rotl)(x05 + x04 | 0, 7); + x07 ^= (0, utils_js_1.rotl)(x06 + x05 | 0, 9); + x04 ^= (0, utils_js_1.rotl)(x07 + x06 | 0, 13); + x05 ^= (0, utils_js_1.rotl)(x04 + x07 | 0, 18); + x11 ^= (0, utils_js_1.rotl)(x10 + x09 | 0, 7); + x08 ^= (0, utils_js_1.rotl)(x11 + x10 | 0, 9); + x09 ^= (0, utils_js_1.rotl)(x08 + x11 | 0, 13); + x10 ^= (0, utils_js_1.rotl)(x09 + x08 | 0, 18); + x12 ^= (0, utils_js_1.rotl)(x15 + x14 | 0, 7); + x13 ^= (0, utils_js_1.rotl)(x12 + x15 | 0, 9); + x14 ^= (0, utils_js_1.rotl)(x13 + x12 | 0, 13); + x15 ^= (0, utils_js_1.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 = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + (0, _assert_js_1.number)(N); + (0, _assert_js_1.number)(r); + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + (0, _assert_js_1.number)(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 + if (N <= 1 || (N & (N - 1)) !== 0 || N > 2 ** 32) { + throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 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 > (2 ** 32 - 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: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (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 = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.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 = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + 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 + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(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(); + } + } + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(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 (0, utils_js_1.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 (0, utils_js_1.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(); + }); + } + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/scrypt.js.map b/src/libMPC/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..340946b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;AAuLA,wBA0BC;AAKD,kCA2BC;AAjPD,6CAAsD;AACtD,2CAAqC;AACrC,2CAAqC;AACrC,yCAAsF;AAEtF,sBAAsB;AAEtB,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAA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CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,eAAI;QAAE,IAAA,qBAAU,EAAC,GAAG,CAAC,CAAC;IAC3B,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha1.d.ts b/src/libMPC/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..f210c5c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,26 @@ +import { HashMD } from './_md.js'; +export declare class SHA1 extends HashMD { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha1.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha1.js b/src/libMPC/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..a6dca1b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = exports.SHA1 = void 0; +const _md_js_1 = require("./_md.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends _md_js_1.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] = (0, utils_js_1.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 = (0, _md_js_1.Chi)(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = (0, _md_js_1.Maj)(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = ((0, utils_js_1.rotl)(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = (0, utils_js_1.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() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.SHA1 = SHA1; +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha1.js.map b/src/libMPC/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..d0e4764 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,qCAA4C;AAC5C,yCAAmD;AAEnD,6EAA6E;AAE7E,gBAAgB;AAChB,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IAC9C,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC3D,CAAC,CAAC;AAEH,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AACnD,MAAa,IAAK,SAAQ,eAAY;IAOpC;QACE,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;QAPlB,MAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAI3B,CAAC;IACS,GAAG;QACX,MAAM,EAAE,CAAC,EA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AAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAhED,oBAgEC;AAED;;;;GAIG;AACU,QAAA,IAAI,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha2.d.ts b/src/libMPC/node_modules/@noble/hashes/sha2.d.ts new file mode 100644 index 0000000..6052a2a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha2.d.ts @@ -0,0 +1,3 @@ +export { sha256, sha224 } from './sha256.js'; +export { sha512, sha512_224, sha512_256, sha384 } from './sha512.js'; +//# sourceMappingURL=sha2.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha2.js b/src/libMPC/node_modules/@noble/hashes/sha2.js new file mode 100644 index 0000000..651b9e4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha2.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.sha224 = exports.sha256 = void 0; +// Usually you either use sha256, or sha512. We re-export them as sha2 for naming consistency. +var sha256_js_1 = require("./sha256.js"); +Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return sha256_js_1.sha256; } }); +Object.defineProperty(exports, "sha224", { enumerable: true, get: function () { return sha256_js_1.sha224; } }); +var sha512_js_1 = require("./sha512.js"); +Object.defineProperty(exports, "sha512", { enumerable: true, get: function () { return sha512_js_1.sha512; } }); +Object.defineProperty(exports, "sha512_224", { enumerable: true, get: function () { return sha512_js_1.sha512_224; } }); +Object.defineProperty(exports, "sha512_256", { enumerable: true, get: function () { return sha512_js_1.sha512_256; } }); +Object.defineProperty(exports, "sha384", { enumerable: true, get: function () { return sha512_js_1.sha384; } }); +//# sourceMappingURL=sha2.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha2.js.map b/src/libMPC/node_modules/@noble/hashes/sha2.js.map new file mode 100644 index 0000000..a0c2748 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.js","sourceRoot":"","sources":["src/sha2.ts"],"names":[],"mappings":";;;AAAA,8FAA8F;AAC9F,yCAA6C;AAApC,mGAAA,MAAM,OAAA;AAAE,mGAAA,MAAM,OAAA;AACvB,yCAAqE;AAA5D,mGAAA,MAAM,OAAA;AAAE,uGAAA,UAAU,OAAA;AAAE,uGAAA,UAAU,OAAA;AAAE,mGAAA,MAAM,OAAA"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha256.d.ts b/src/libMPC/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..b31a842 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,37 @@ +import { HashMD } from './_md.js'; +export declare class SHA256 extends HashMD { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +/** + * SHA2-224 hash function + */ +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha256.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha256.js b/src/libMPC/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..3e21558 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,130 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = exports.SHA256 = void 0; +const _md_js_1 = require("./_md.js"); +const utils_js_1 = require("./utils.js"); +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 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 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends _md_js_1.HashMD { + constructor() { + super(64, 32, 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 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.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 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + (0, _md_js_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + (0, _md_js_1.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() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.SHA256 = SHA256; +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +/** + * SHA2-224 hash function + */ +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha256.js.map b/src/libMPC/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..2b14c2e --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["src/sha256.ts"],"names":[],"mappings":";;;AAAA,qCAA4C;AAC5C,yCAAmD;AAEnD,gEAAgE;AAChE,0DAA0D;AAE1D,mBAAmB;AACnB,yFAAyF;AACzF,kBAAkB;AAClB,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IAC/C,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,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,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AA5ED,wBA4EC;AACD,4EAA4E;AAC5E,MAAM,MAAO,SAAQ,MAAM;IASzB;QACE,KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E;;GAEG;AACU,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3-addons.d.ts b/src/libMPC/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..151cdf2 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,154 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): HashXOF; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): HashXOF; +}; +export declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +export declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type TurboshakeOpts = ShakeOpts & { + D?: number; +}; +export declare const turboshake128: { + (msg: Input, opts?: TurboshakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: TurboshakeOpts): HashXOF>; +}; +export declare const turboshake256: { + (msg: Input, opts?: TurboshakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: TurboshakeOpts): HashXOF>; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +export declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(_out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; +//# sourceMappingURL=sha3-addons.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3-addons.js b/src/libMPC/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..5f2a4d4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,365 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.KeccakPRG = exports.m14 = exports.k12 = exports.KangarooTwelve = exports.turboshake256 = exports.turboshake128 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.ParallelHash = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.TupleHash = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.KMAC = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +exports.KMAC = KMAC; +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +exports.TupleHash = TupleHash; +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +exports.ParallelHash = ParallelHash; +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +const genTurboshake = (blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => { + const D = opts.D === undefined ? 0x1f : opts.D; + // Section 2.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/ + if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f) + throw new Error(`turboshake: wrong domain separation byte: ${D}, should be 0x01..0x7f`); + return new sha3_js_1.Keccak(blockLen, D, opts.dkLen === undefined ? outputLen : opts.dkLen, true, 12); +}); +exports.turboshake128 = genTurboshake(168, 256 / 8); +exports.turboshake256 = genTurboshake(136, 512 / 8); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +exports.KangarooTwelve = KangarooTwelve; +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +exports.KeccakPRG = KeccakPRG; +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3-addons.js.map b/src/libMPC/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..589e3e5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAQoB;AACpB,uCAA8C;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GA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AAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAtDD,8BAsDC;AAEM,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAAxD,QAAA,SAAS,aAA+C"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3.d.ts b/src/libMPC/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..82b88a8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,98 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +//# sourceMappingURL=sha3.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3.js b/src/libMPC/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..cb0b719 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,219 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = void 0; +exports.keccakP = keccakP; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); + keccakP(this.state32, this.rounds); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha3.js.map b/src/libMPC/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..1dc4d71 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["src/sha3.ts"],"names":[],"mappings":";;;AAgDA,0BAyCC;AAzFD,6CAA6D;AAC7D,uCAAkE;AAClE,yCAUoB;AAEpB,oGAAoG;AACpG,iCAAiC;AAEjC,2CAA2C;AAC3C,MAAM,OAAO,GAAa,EAAE,CAAC;AAC7B,MAAM,SAAS,GAAa,EAAE,CAAC;AAC/B,MAAM,UAAU,GAAa,EAAE,CAAC;AAChC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAA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2282d2b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,124 @@ +import { HashMD } from './_md.js'; +export declare class SHA512 extends HashMD { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare class SHA512_224 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare class SHA512_256 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare class SHA384 extends SHA512 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +//# sourceMappingURL=sha512.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha512.js b/src/libMPC/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..a793ba6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,238 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA384 = exports.SHA512_256 = exports.SHA512_224 = exports.SHA512 = void 0; +const _md_js_1 = require("./_md.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.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))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends _md_js_1.HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 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_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.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_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.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_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.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_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.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_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.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_js_1.default.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_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.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() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +exports.SHA512_224 = SHA512_224; +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +exports.SHA512_256 = SHA512_256; +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.SHA384 = SHA384; +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/sha512.js.map b/src/libMPC/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..7836e7c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,uCAA4B;AAC5B,yCAA6C;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAA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AE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QAIlB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAvBD,wBAuBC;AAEY,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/src/_assert.ts b/src/libMPC/node_modules/@noble/hashes/src/_assert.ts new file mode 100644 index 0000000..12e98f5 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,51 @@ +function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`); +} + +function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`); +} + +// copied from utils +export function isBytes(a: unknown): a is Uint8Array { + return ( + a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array') + ); +} + +function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!isBytes(b)) throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +function hash(h: Hash) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} + +function exists(instance: any, 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'); +} +function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +export { number, bool, bytes, hash, exists, output }; + +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; diff --git a/src/libMPC/node_modules/@noble/hashes/src/_blake.ts b/src/libMPC/node_modules/@noble/hashes/src/_blake.ts new file mode 100644 index 0000000..d455be6 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/_blake.ts @@ -0,0 +1,134 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, Input, toBytes, u32, isLE, byteSwap32, byteSwapIfBE } from './utils.js'; + +// Blake is based on ChaCha permutation. + +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + if (!isLE) byteSwap32(buffer32); + this.compress(buffer32, 0, false); + if (!isLE) byteSwap32(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + if (!isLE) byteSwap32(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + if (!isLE) byteSwap32(data32); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + if (!isLE) byteSwap32(buffer32); + this.compress(buffer32, 0, true); + if (!isLE) byteSwap32(buffer32); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = byteSwapIfBE(v))); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/src/libMPC/node_modules/@noble/hashes/src/_md.ts b/src/libMPC/node_modules/@noble/hashes/src/_md.ts new file mode 100644 index 0000000..c78cf26 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/_md.ts @@ -0,0 +1,134 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +/** + * Polyfill for Safari 14 + */ +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + 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 const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); + +/** + * Majority function, true if any two inputs is true + */ +export const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +export abstract class HashMD> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + 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: Uint8Array) { + exists(this); + output(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; + this.buffer.subarray(pos).fill(0); + // 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?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/src/libMPC/node_modules/@noble/hashes/src/_u64.ts b/src/libMPC/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..efc55b4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,77 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n: bigint, 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: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, _l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h: number, l: number) => l; +const rotr32L = (h: number, _l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (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: number, Al: number, Bh: number, Bl: number) { + 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: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +export { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// 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; diff --git a/src/libMPC/node_modules/@noble/hashes/src/argon2.ts b/src/libMPC/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..b29083b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +const enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const A2_BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = A2_BUF[2*a], Ah = A2_BUF[2*a + 1]; // prettier-ignore + let Bl = A2_BUF[2*b], Bh = A2_BUF[2*b + 1]; // prettier-ignore + let Cl = A2_BUF[2*c], Ch = A2_BUF[2*c + 1]; // prettier-ignore + let Dl = A2_BUF[2*d], Dh = A2_BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + + (A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah); + (A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh); + (A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch); + (A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) A2_BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // 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(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/src/libMPC/node_modules/@noble/hashes/src/blake2b.ts b/src/libMPC/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..2e57434 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,205 @@ +import { BLAKE, BlakeOpts, SIGMA } from './_blake.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts, byteSwapIfBE } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const B2B_IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BBUF = /* @__PURE__ */ new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} + +function G2b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); + (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); + (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); + (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); +} + +export class BLAKE2b extends BLAKE { + // Same as SHA-512, but LE + private v0l = B2B_IV[0] | 0; + private v0h = B2B_IV[1] | 0; + private v1l = B2B_IV[2] | 0; + private v1h = B2B_IV[3] | 0; + private v2l = B2B_IV[4] | 0; + private v2h = B2B_IV[5] | 0; + private v3l = B2B_IV[6] | 0; + private v3h = B2B_IV[7] | 0; + private v4l = B2B_IV[8] | 0; + private v4h = B2B_IV[9] | 0; + private v5l = B2B_IV[10] | 0; + private v5h = B2B_IV[11] | 0; + private v6l = B2B_IV[12] | 0; + private v6h = B2B_IV[13] | 0; + private v7l = B2B_IV[14] | 0; + private v7h = B2B_IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= byteSwapIfBE(salt[0]); + this.v4h ^= byteSwapIfBE(salt[1]); + this.v5l ^= byteSwapIfBE(salt[2]); + this.v5h ^= byteSwapIfBE(salt[3]); + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= byteSwapIfBE(pers[0]); + this.v6h ^= byteSwapIfBE(pers[1]); + this.v7l ^= byteSwapIfBE(pers[2]); + this.v7h ^= byteSwapIfBE(pers[3]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(B2B_IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + BBUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2b(opts) +); diff --git a/src/libMPC/node_modules/@noble/hashes/src/blake2s.ts b/src/libMPC/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..89499ad --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,138 @@ +import { BLAKE, BlakeOpts, SIGMA } from './_blake.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32, byteSwapIfBE } from './utils.js'; + +// Initial state: same as SHA256 +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +export const B2S_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Mixing function G splitted in two halfs +function G1s(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2s(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} + +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +export class BLAKE2s extends BLAKE { + // Internal state, same as SHA-256 + private v0 = B2S_IV[0] | 0; + private v1 = B2S_IV[1] | 0; + private v2 = B2S_IV[2] | 0; + private v3 = B2S_IV[3] | 0; + private v4 = B2S_IV[4] | 0; + private v5 = B2S_IV[5] | 0; + private v6 = B2S_IV[6] | 0; + private v7 = B2S_IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= byteSwapIfBE(salt[0]); + this.v5 ^= byteSwapIfBE(salt[1]); + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= byteSwapIfBE(pers[0]); + this.v7 ^= byteSwapIfBE(pers[1]); + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2s(opts) +); diff --git a/src/libMPC/node_modules/@noble/hashes/src/blake3.ts b/src/libMPC/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..e2d566f --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,268 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE } from './_blake.js'; +import { compress, B2S_IV } from './blake2s.js'; +import { + Input, + u8, + u32, + toBytes, + HashXOF, + wrapXOFConstructorWithOpts, + isLE, + byteSwap32, +} from './utils.js'; + +// Blake3 is single-option Blake2 with reduced security (round count). + +// Flag bitset +const enum B3_Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +export class BLAKE3 extends BLAKE implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + if (!isLE) byteSwap32(this.IV); + this.flags = flags | B3_Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + if (!isLE) byteSwap32(this.IV); + this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = B2S_IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= B3_Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= B3_Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + if (!isLE) byteSwap32(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + if (!isLE) { + byteSwap32(buffer32); + byteSwap32(out32); + } + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | B3_Flags.ROOT; + if (this.stack.length) { + flags |= B3_Flags.PARENT; + if (!isLE) byteSwap32(this.buffer32); + this.compress(this.buffer32, 0, true); + if (!isLE) byteSwap32(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts( + (opts) => new BLAKE3(opts) +); diff --git a/src/libMPC/node_modules/@noble/hashes/src/crypto.ts b/src/libMPC/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/src/libMPC/node_modules/@noble/hashes/src/cryptoNode.ts b/src/libMPC/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..e872405 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,11 @@ +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 +// See utils.ts for details. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc + ? (nc.webcrypto as any) + : nc && typeof nc === 'object' && 'randomBytes' in nc + ? nc + : undefined; diff --git a/src/libMPC/node_modules/@noble/hashes/src/eskdf.ts b/src/libMPC/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..5b78d57 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,181 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +export interface ESKDF { + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +} + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): Promise { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/src/libMPC/node_modules/@noble/hashes/src/hkdf.ts b/src/libMPC/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..6d880d1 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/src/libMPC/node_modules/@noble/hashes/src/hmac.ts b/src/libMPC/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..79cc29b --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,85 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + 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() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assertExists(this); + assertBytes(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?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + 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; + } + 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: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/src/libMPC/node_modules/@noble/hashes/src/index.ts b/src/libMPC/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..6afa9aa --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/src/libMPC/node_modules/@noble/hashes/src/pbkdf2.ts b/src/libMPC/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..b5f7e6a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_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: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + 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 + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // 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); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // 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); +} diff --git a/src/libMPC/node_modules/@noble/hashes/src/ripemd160.ts b/src/libMPC/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..5f15efd --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,108 @@ +import { HashMD } from './_md.js'; +import { rotl, wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = /* @__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) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends HashMD { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) R_BUF[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 = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[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 + f(rGroup, br, cr, dr) + R_BUF[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 + ); + } + protected roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); diff --git a/src/libMPC/node_modules/@noble/hashes/src/scrypt.ts b/src/libMPC/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..1daa551 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,242 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { rotl, asyncLoop, checkOpts, Input, u32, isLE, byteSwap32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // 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: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // 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]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // 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; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(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 + if (N <= 1 || (N & (N - 1)) !== 0 || N > 2 ** 32) { + throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 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 > (2 ** 32 - 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: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (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: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + 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 + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + if (!isLE) byteSwap32(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(); + } + } + if (!isLE) byteSwap32(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + if (!isLE) byteSwap32(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(); + }); + } + if (!isLE) byteSwap32(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha1.ts b/src/libMPC/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..671b007 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,85 @@ +import { HashMD, Chi, Maj } from './_md.js'; +import { rotl, wrapConstructor } from './utils.js'; + +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. + +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +export class SHA1 extends HashMD { + private A = SHA1_IV[0] | 0; + private B = SHA1_IV[1] | 0; + private C = SHA1_IV[2] | 0; + private D = SHA1_IV[3] | 0; + private E = SHA1_IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + 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); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha2.ts b/src/libMPC/node_modules/@noble/hashes/src/sha2.ts new file mode 100644 index 0000000..33e5914 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha2.ts @@ -0,0 +1,3 @@ +// Usually you either use sha256, or sha512. We re-export them as sha2 for naming consistency. +export { sha256, sha224 } from './sha256.js'; +export { sha512, sha512_224, sha512_256, sha384 } from './sha512.js'; diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha256.ts b/src/libMPC/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..1b6b08a --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,132 @@ +import { HashMD, Chi, Maj } from './_md.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 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 +]); + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +export class SHA256 extends HashMD { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = SHA256_IV[0] | 0; + B = SHA256_IV[1] | 0; + C = SHA256_IV[2] | 0; + D = SHA256_IV[3] | 0; + E = SHA256_IV[4] | 0; + F = SHA256_IV[5] | 0; + G = SHA256_IV[6] | 0; + H = SHA256_IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + 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; + } + protected process(view: DataView, offset: number): void { + // 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); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha3-addons.ts b/src/libMPC/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..4f1da80 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,423 @@ +import { number as assertNumber } from './_assert.js'; +import { + Input, + toBytes, + wrapConstructorWithOpts, + u32, + Hash, + HashXOF, + wrapXOFConstructorWithOpts, +} from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +export class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +export class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +export class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Should be simple 'shake with 12 rounds', but no, we got whole new spec about Turbo SHAKE Pro MAX. +export type TurboshakeOpts = ShakeOpts & { + D?: number; // Domain separation byte +}; + +const genTurboshake = (blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, TurboshakeOpts>((opts: TurboshakeOpts = {}) => { + const D = opts.D === undefined ? 0x1f : opts.D; + // Section 2.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/ + if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f) + throw new Error(`turboshake: wrong domain separation byte: ${D}, should be 0x01..0x7f`); + return new Keccak(blockLen, D, opts.dkLen === undefined ? outputLen : opts.dkLen, true, 12); + }); + +export const turboshake128 = /* @__PURE__ */ genTurboshake(168, 256 / 8); +export const turboshake256 = /* @__PURE__ */ genTurboshake(136, 512 / 8); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +export class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +export class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(_out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha3.ts b/src/libMPC/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..12df903 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,229 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, + isLE, + byteSwap32, +} from './utils.js'; + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. + +// Various per round constants calculations +const SHA3_PI: number[] = []; +const SHA3_ROTL: number[] = []; +const _SHA3_IOTA: bigint[] = []; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + if (!isLE) byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); diff --git a/src/libMPC/node_modules/@noble/hashes/src/sha512.ts b/src/libMPC/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..18b0ad9 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,246 @@ +import { HashMD } from './_md.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__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))))(); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends HashMD { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + 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 + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + 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; + } + protected process(view: DataView, offset: number) { + // 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); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +export class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +export class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +export class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); diff --git a/src/libMPC/node_modules/@noble/hashes/src/utils.ts b/src/libMPC/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..40cad6c --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,260 @@ +/*! 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'; +import { bytes as abytes } from './_assert.js'; +// export { isBytes } from './_assert.js'; +// We can't reuse isBytes from _assert, because somehow this causes huge perf issues +export function isBytes(a: unknown): a is Uint8Array { + return ( + a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array') + ); +} + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +export const rotl = (word: number, shift: number) => + (word << shift) | ((word >>> (32 - shift)) >>> 0); + +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +export const byteSwap = (word: number) => + ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// Conditionally byte swap if on a big-endian platform +export const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n); + +// In place byte swap for Uint32Array +export function byteSwap32(arr: Uint32Array) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} + +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + abytes(bytes); + // 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 } as const; +function asciiToBase16(char: number): number | undefined { + if (char >= asciis._0 && char <= asciis._9) return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10); + return; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) throw new Error('padded 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; + } + 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: number, tick: number, cb: (i: number) => void) { + 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; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * 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: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + abytes(data); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + 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; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +const toStr = {}.toString; +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto && typeof crypto.randomBytes === 'function') { + return crypto.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/src/libMPC/node_modules/@noble/hashes/utils.d.ts b/src/libMPC/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..21254c4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,96 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export declare function isBytes(a: unknown): a is Uint8Array; +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const rotl: (word: number, shift: number) => number; +export declare const isLE: boolean; +export declare const byteSwap: (word: number) => number; +export declare const byteSwapIfBE: (n: number) => number; +export declare function byteSwap32(arr: Uint32Array): void; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * 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 declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/utils.js b/src/libMPC/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..106acd4 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/utils.js @@ -0,0 +1,215 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Hash = exports.nextTick = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +exports.isBytes = isBytes; +exports.byteSwap32 = byteSwap32; +exports.bytesToHex = bytesToHex; +exports.hexToBytes = hexToBytes; +exports.asyncLoop = asyncLoop; +exports.utf8ToBytes = utf8ToBytes; +exports.toBytes = toBytes; +exports.concatBytes = concatBytes; +exports.checkOpts = checkOpts; +exports.wrapConstructor = wrapConstructor; +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +exports.randomBytes = randomBytes; +// 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. +const crypto_1 = require("@noble/hashes/crypto"); +const _assert_js_1 = require("./_assert.js"); +// export { isBytes } from './_assert.js'; +// We can't reuse isBytes from _assert, because somehow this causes huge perf issues +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +exports.rotl = rotl; +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +exports.byteSwap = byteSwap; +// Conditionally byte swap if on a big-endian platform +exports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = (0, exports.byteSwap)(arr[i]); + } +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + (0, _assert_js_1.bytes)(bytes); + // 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(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded 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; + } + 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. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +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 (0, exports.nextTick)(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * 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. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + (0, _assert_js_1.bytes)(data); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + (0, _assert_js_1.bytes)(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; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +function wrapConstructor(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; +} +function wrapConstructorWithOpts(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; +} +function wrapXOFConstructorWithOpts(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; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') { + return crypto_1.crypto.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/hashes/utils.js.map b/src/libMPC/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..da1bf59 --- /dev/null +++ b/src/libMPC/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAYtE,0BAKC;AAgCD,gCAIC;AASD,gCAQC;AAcD,gCAgBC;AAQD,8BAUC;AASD,kCAGC;AAQD,0BAIC;AAKD,kCAcC;AA2CD,8BAQC;AAID,0CAOC;AAED,0DASC;AAED,gEASC;AAKD,kCASC;AAjQD,oFAAoF;AACp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D,CAAC;IACD,+BAA+B;IAC/B,IAAI,eAAM,IAAI,OAAO,eAAM,CAAC,WAAW,KAAK,UAAU,EAAE,CAAC;QACvD,OAAO,eAAM,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;IACzC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/secp256k1/LICENSE b/src/libMPC/node_modules/@noble/secp256k1/LICENSE new file mode 100644 index 0000000..a5e0151 --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/src/libMPC/node_modules/@noble/secp256k1/README.md b/src/libMPC/node_modules/@noble/secp256k1/README.md new file mode 100644 index 0000000..f4e0a5d --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/README.md @@ -0,0 +1,352 @@ +# noble-secp256k1 + +Fastest 4KB JS implementation of secp256k1 signatures & ECDH. + +- ✍️ Deterministic [ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm) + signatures compliant with [RFC6979](https://www.rfc-editor.org/rfc/rfc6979) +- 🤝 Elliptic Curve Diffie-Hellman [ECDH](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie–Hellman) +- 📦 Pure ESM, can be imported without transpilers +- 🪶 4KB gzipped, 450 lines of code + +Use larger drop-in replacement [noble-curves](https://github.com/paulmillr/noble-curves) instead, +if you need additional features such as common.js, Schnorr signatures, DER encoding or support for different hash functions. To upgrade from v1 to v2, see [Upgrading](#upgrading). + +### This library belongs to _noble_ cryptography + +> **noble-cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds with provenance +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) + +## Usage + +> npm install @noble/secp256k1 + +We support all major platforms and runtimes. For node.js <= 18 and React Native, additional polyfills are needed: see below. + +```js +import * as secp from '@noble/secp256k1'; +// import * as secp from "https://deno.land/x/secp256k1/mod.ts"; // Deno +// import * as secp from "https://unpkg.com/@noble/secp256k1"; // Unpkg +(async () => { + // keys, messages & other inputs can be Uint8Arrays or hex strings + // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) === 'deadbeef' + const privKey = secp.utils.randomPrivateKey(); // Secure random private key + // sha256 of 'hello world' + const msgHash = 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'; + const pubKey = secp.getPublicKey(privKey); + const signature = await secp.signAsync(msgHash, privKey); // Sync methods below + const isValid = secp.verify(signature, msgHash, pubKey); + + const alicesPubkey = secp.getPublicKey(secp.utils.randomPrivateKey()); + secp.getSharedSecret(privKey, alicesPubkey); // Elliptic curve diffie-hellman + signature.recoverPublicKey(msgHash); // Public key recovery +})(); +``` + +Additional polyfills for some environments: + +```ts +// 1. Enable synchronous methods. +// Only async methods are available by default, to keep the library dependency-free. +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +secp.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp.etc.concatBytes(...m)) +// Sync methods can be used now: +// secp.sign(msgHash, privKey); + +// 2. node.js 18 and older, requires polyfilling globalThis.crypto +import { webcrypto } from 'node:crypto'; +// @ts-ignore +if (!globalThis.crypto) globalThis.crypto = webcrypto; + +// 3. React Native needs crypto.getRandomValues polyfill and sha512 +import 'react-native-get-random-values'; +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +secp.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp.etc.concatBytes(...m)); +secp.etc.hmacSha256Async = (k, ...m) => Promise.resolve(secp.etc.hmacSha256Sync(k, ...m)); +``` + +## API + +There are 3 main methods: `getPublicKey(privateKey)`, +`sign(messageHash, privateKey)` and +`verify(signature, messageHash, publicKey)`. +We accept Hex type everywhere: + +```ts +type Hex = Uint8Array | string +``` + +### getPublicKey + +```ts +function getPublicKey(privateKey: Hex, isCompressed?: boolean): Uint8Array; +``` + +Generates 33-byte compressed public key from 32-byte private key. + +- If you need uncompressed 65-byte public key, set second argument to `false`. +- Use `ProjectivePoint.fromPrivateKey(privateKey)` for Point instance. +- Use `ProjectivePoint.fromHex(publicKey)` to convert Hex / Uint8Array into Point. + +### sign + +```ts +function sign( + messageHash: Hex, // message hash (not message) which would be signed + privateKey: Hex, // private key which will sign the hash + opts?: { lowS: boolean, extraEntropy: boolean | Hex } // optional params +): Signature; +function signAsync( + messageHash: Hex, + privateKey: Hex, + opts?: { lowS: boolean; extraEntropy: boolean | Hex } +): Promise; + +sign(msgHash, privKey, { lowS: false }); // Malleable signature +sign(msgHash, privKey, { extraEntropy: true }); // Improved security +``` + +Generates low-s deterministic-k RFC6979 ECDSA signature. Assumes hash of message, +which means you'll need to do something like `sha256(message)` before signing. + +1. `lowS: false` allows to create malleable signatures, for compatibility with openssl. + Default `lowS: true` prohibits signatures which have (sig.s >= CURVE.n/2n) and is compatible with BTC/ETH. +2. `extraEntropy: true` improves security by adding entropy, follows section 3.6 of RFC6979: + - No disadvantage: if an entropy generator is broken, sigs would be the same + as they are without the option + - It would help a lot in case there is an error somewhere in `k` gen. + Exposing `k` could leak private keys + - Sigs with extra entropy would have different `r` / `s`, which means they + would still be valid, but may break some test vectors if you're + cross-testing against other libs + +### verify + +```ts +function verify( + signature: Hex | Signature, // returned by the `sign` function + messageHash: Hex, // message hash (not message) that must be verified + publicKey: Hex, // public (not private) key + opts?: { lowS: boolean } // optional params; { lowS: true } by default +): boolean; +``` + +Verifies ECDSA signature and ensures it has lowS (compatible with BTC/ETH). +`lowS: false` turns off malleability check, but makes it OpenSSL-compatible. + +### getSharedSecret + +```ts +function getSharedSecret( + privateKeyA: Uint8Array | string, // Alices's private key + publicKeyB: Uint8Array | string, // Bob's public key + isCompressed = true // optional arg. (default) true=33b key, false=65b. +): Uint8Array; +``` + +Computes ECDH (Elliptic Curve Diffie-Hellman) shared secret between +key A and different key B. + +Use `ProjectivePoint.fromHex(publicKeyB).multiply(privateKeyA)` for Point instance + +### recoverPublicKey + +```ts +signature.recoverPublicKey( + msgHash: Uint8Array | string +): Uint8Array | undefined; +``` + +Recover public key from Signature instance with `recovery` bit set. + +### utils + +A bunch of useful **utilities** are also exposed: + +```typescript +type Bytes = Uint8Array; +const etc: { + hexToBytes: (hex: string) => Bytes; + bytesToHex: (b: Bytes) => string; + concatBytes: (...arrs: Bytes[]) => Bytes; + bytesToNumberBE: (b: Bytes) => bigint; + numberToBytesBE: (num: bigint) => Bytes; + mod: (a: bigint, b?: bigint) => bigint; + invert: (num: bigint, md?: bigint) => bigint; + hmacSha256Async: (key: Bytes, ...msgs: Bytes[]) => Promise; + hmacSha256Sync: HmacFnSync; + hashToPrivateKey: (hash: Hex) => Bytes; + randomBytes: (len: number) => Bytes; +}; +const utils: { + normPrivateKeyToScalar: (p: PrivKey) => bigint; + randomPrivateKey: () => Bytes; // Uses CSPRNG https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + isValidPrivateKey: (key: Hex) => boolean; + precompute(p: ProjectivePoint, windowSize?: number): ProjectivePoint; +}; +class ProjectivePoint { + constructor(px: bigint, py: bigint, pz: bigint); + static readonly BASE: ProjectivePoint; + static readonly ZERO: ProjectivePoint; + static fromAffine(point: AffinePoint): ProjectivePoint; + static fromHex(hex: Hex): ProjectivePoint; + static fromPrivateKey(n: PrivKey): ProjectivePoint; + get x(): bigint; + get y(): bigint; + add(other: ProjectivePoint): ProjectivePoint; + assertValidity(): void; + equals(other: ProjectivePoint): boolean; + multiply(n: bigint): ProjectivePoint; + negate(): ProjectivePoint; + subtract(other: ProjectivePoint): ProjectivePoint; + toAffine(): AffinePoint; + toHex(isCompressed?: boolean): string; + toRawBytes(isCompressed?: boolean): Bytes; +} +class Signature { + constructor(r: bigint, s: bigint, recovery?: number | undefined); + static fromCompact(hex: Hex): Signature; + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number | undefined; + ok(): Signature; + hasHighS(): boolean; + normalizeS(): Signature; + recoverPublicKey(msgh: Hex): Point; + toCompactRawBytes(): Bytes; + toCompactHex(): string; +} +CURVE // curve prime; order; equation params, generator coordinates +``` + +## Security + +The module is production-ready. +It is cross-tested against [noble-curves](https://github.com/paulmillr/noble-curves), +and has similar security. + +1. The current version is rewrite of v1, which has been audited by cure53: +[PDF](https://cure53.de/pentest-report_noble-lib.pdf) (funded by [Umbra.cash](https://umbra.cash) & community). +2. It's being fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz): +run the fuzzer by yourself to check. + +Our EC multiplication is hardened to be algorithmically constant time. +We're using built-in JS `BigInt`, which is potentially vulnerable to +[timing attacks](https://en.wikipedia.org/wiki/Timing_attack) as +[per MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#cryptography). +But, _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard +to achieve in a scripting language. Which means _any other JS library doesn't +use constant-time bigints_. Including bn.js or anything else. +Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — +including bindings to native ones. Use low-level libraries & languages. + +We consider infrastructure attacks like rogue NPM modules very important; +that's why it's crucial to minimize the amount of 3rd-party dependencies & native +bindings. If your app uses 500 dependencies, any dep could get hacked and you'll +be downloading malware with every `npm install`. Our goal is to minimize this attack vector. + +As for key generation, we're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +## Speed + +Use [noble-curves](https://github.com/paulmillr/noble-curves) if you need even higher performance. + +Benchmarks measured with Apple M2 on MacOS 13 with node.js 20. + + getPublicKey(utils.randomPrivateKey()) x 6,430 ops/sec @ 155μs/op + sign x 3,367 ops/sec @ 296μs/op + verify x 600 ops/sec @ 1ms/op + getSharedSecret x 505 ops/sec @ 1ms/op + recoverPublicKey x 612 ops/sec @ 1ms/op + Point.fromHex (decompression) x 9,185 ops/sec @ 108μs/op + +Compare to other libraries on M1 (`openssl` uses native bindings, not JS): + + elliptic#getPublicKey x 1,940 ops/sec + sjcl#getPublicKey x 211 ops/sec + + elliptic#sign x 1,808 ops/sec + sjcl#sign x 199 ops/sec + openssl#sign x 4,243 ops/sec + ecdsa#sign x 116 ops/sec + + elliptic#verify x 812 ops/sec + sjcl#verify x 166 ops/sec + openssl#verify x 4,452 ops/sec + ecdsa#verify x 80 ops/sec + + elliptic#ecdh x 971 ops/sec + +## Contributing + +1. Clone the repository. +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm test` to run jest on `test/index.ts` + +Special thanks to [Roman Koblov](https://github.com/romankoblov), who have +helped to improve scalar multiplication speed. + +## Upgrading + +noble-secp256k1 v2 features improved security and smaller attack surface. +The goal of v2 is to provide minimum possible JS library which is safe and fast. + +That means the library was reduced 4x, to just over 400 lines. In order to +achieve the goal, **some features were moved** to +[noble-curves](https://github.com/paulmillr/noble-curves), which is +even safer and faster drop-in replacement library with same API. +Switch to curves if you intend to keep using these features: + +- DER encoding: toDERHex, toDERRawBytes, signing / verification of DER sigs +- Schnorr signatures +- Using `utils.precompute()` for non-base point +- Support for environments which don't support bigint literals +- Common.js support +- Support for node.js 18 and older without [shim](#usage) + +Other changes for upgrading from @noble/secp256k1 1.7 to 2.0: + +- `getPublicKey` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getPublicKey(priv, false)` +- `sign` + - is now sync; use `signAsync` for async version + - now returns `Signature` instance with `{ r, s, recovery }` properties + - `canonical` option was renamed to `lowS` + - `recovered` option has been removed because recovery bit is always returned now + - `der` option has been removed. There are 2 options: + 1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`. + Compact encoding is simply a concatenation of 32-byte r and 32-byte s. + 2. If you must use DER encoding, switch to noble-curves (see above). +- `verify` + - `strict` option was renamed to `lowS` +- `getSharedSecret` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getSharedSecret(a, b, false)` +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `number` type for private keys have been removed: use `bigint` instead +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`hmacSha256Sync` and others) + +## License + +MIT (c) Paul Miller [(https://paulmillr.com)](https://paulmillr.com), see LICENSE file. diff --git a/src/libMPC/node_modules/@noble/secp256k1/index.d.ts b/src/libMPC/node_modules/@noble/secp256k1/index.d.ts new file mode 100644 index 0000000..bdf1be8 --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/index.d.ts @@ -0,0 +1,98 @@ +declare const CURVE: { + p: bigint; + n: bigint; + a: bigint; + b: bigint; + Gx: bigint; + Gy: bigint; +}; +type Bytes = Uint8Array; +type Hex = Bytes | string; +type PrivKey = Hex | bigint; +interface AffinePoint { + x: bigint; + y: bigint; +} +declare class Point { + readonly px: bigint; + readonly py: bigint; + readonly pz: bigint; + constructor(px: bigint, py: bigint, pz: bigint); + static readonly BASE: Point; + static readonly ZERO: Point; + static fromAffine(p: AffinePoint): Point; + static fromHex(hex: Hex): Point; + static fromPrivateKey(k: PrivKey): Point; + get x(): bigint; + get y(): bigint; + equals(other: Point): boolean; + negate(): Point; + double(): Point; + add(other: Point): Point; + mul(n: bigint, safe?: boolean): Point; + mulAddQUns(R: Point, u1: bigint, u2: bigint): Point; + toAffine(): AffinePoint; + assertValidity(): Point; + multiply(n: bigint): Point; + aff(): AffinePoint; + ok(): Point; + toHex(isCompressed?: boolean): string; + toRawBytes(isCompressed?: boolean): Uint8Array; +} +declare function getPublicKey(privKey: PrivKey, isCompressed?: boolean): Uint8Array; +type SignatureWithRecovery = Signature & { + recovery: number; +}; +declare class Signature { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number | undefined; + constructor(r: bigint, s: bigint, recovery?: number | undefined); + static fromCompact(hex: Hex): Signature; + assertValidity(): this; + addRecoveryBit(rec: number): SignatureWithRecovery; + hasHighS(): boolean; + normalizeS(): Signature; + recoverPublicKey(msgh: Hex): Point; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; +} +type HmacFnSync = undefined | ((key: Bytes, ...msgs: Bytes[]) => Bytes); +declare function signAsync(msgh: Hex, priv: PrivKey, opts?: { + lowS?: boolean | undefined; + extraEntropy?: boolean | Hex | undefined; +}): Promise; +declare function sign(msgh: Hex, priv: PrivKey, opts?: { + lowS?: boolean | undefined; + extraEntropy?: boolean | Hex | undefined; +}): SignatureWithRecovery; +type SigLike = { + r: bigint; + s: bigint; +}; +declare function verify(sig: Hex | SigLike, msgh: Hex, pub: Hex, opts?: { + lowS?: boolean | undefined; +}): boolean; +declare function getSharedSecret(privA: Hex, pubB: Hex, isCompressed?: boolean): Bytes; +declare function hashToPrivateKey(hash: Hex): Bytes; +declare const etc: { + hexToBytes: (hex: string) => Bytes; + bytesToHex: (b: Bytes) => string; + concatBytes: (...arrs: Bytes[]) => Uint8Array; + bytesToNumberBE: (b: Bytes) => bigint; + numberToBytesBE: (num: bigint) => Bytes; + mod: (a: bigint, b?: bigint) => bigint; + invert: (num: bigint, md?: bigint) => bigint; + hmacSha256Async: (key: Bytes, ...msgs: Bytes[]) => Promise; + hmacSha256Sync: HmacFnSync; + hashToPrivateKey: typeof hashToPrivateKey; + randomBytes: (len?: number) => Bytes; +}; +declare const utils: { + normPrivateKeyToScalar: (p: PrivKey) => bigint; + isValidPrivateKey: (key: Hex) => boolean; + randomPrivateKey: () => Bytes; + precompute(w?: number, p?: Point): Point; +}; +export { getPublicKey, sign, signAsync, verify, CURVE, // Remove the export to easily use in REPL +getSharedSecret, etc, utils, Point as ProjectivePoint, Signature }; diff --git a/src/libMPC/node_modules/@noble/secp256k1/index.js b/src/libMPC/node_modules/@noble/secp256k1/index.js new file mode 100644 index 0000000..f405b3b --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/index.js @@ -0,0 +1,517 @@ +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +const B256 = 2n ** 256n; // secp256k1 is short weierstrass curve +const P = B256 - 0x1000003d1n; // curve's field prime +const N = B256 - 0x14551231950b75fc4402da1732fc9bebfn; // curve (group) order +const Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n; // base point x +const Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n; // base point y +const CURVE = { p: P, n: N, a: 0n, b: 7n, Gx, Gy }; // exported variables incl. a, b +const fLen = 32; // field / group byte length +const crv = (x) => mod(mod(x * x) * x + CURVE.b); // x³ + ax + b weierstrass formula; a=0 +const err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace +const big = (n) => typeof n === 'bigint'; // is big integer +const str = (s) => typeof s === 'string'; // is string +const fe = (n) => big(n) && 0n < n && n < P; // is field element (invertible) +const ge = (n) => big(n) && 0n < n && n < N; // is group element +const isu8 = (a) => (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +const au8 = (a, l) => // assert is Uint8Array (of specific length) + !isu8(a) || (typeof l === 'number' && l > 0 && a.length !== l) ? + err('Uint8Array expected') : a; +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(au8(a)), len); // norm(hex/u8a) to u8a +const mod = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division +const isPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is 3d point +class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + } //3d=less inversions + static fromAffine(p) { + return ((p.x === 0n) && (p.y === 0n)) ? Point.ZERO : new Point(p.x, p.y, 1n); + } + static fromHex(hex) { + hex = toU8(hex); // convert hex string to Uint8Array + let p = undefined; + const head = hex[0], tail = hex.subarray(1); // first byte is prefix, rest is data + const x = slcNum(tail, 0, fLen), len = hex.length; // next 32 bytes are x coordinate + if (len === 33 && [0x02, 0x03].includes(head)) { // compressed points: 33b, start + if (!fe(x)) + err('Point hex invalid: x not FE'); // with byte 0x02 or 0x03. Check if 0 0n; d = d.double(), n >>= 1n) { // double-and-add ladder + if (n & 1n) + p = p.add(d); // if bit is present, add to point + else if (safe) + f = f.add(d); // if not, add to fake for timing safety + } + return p; + } + mulAddQUns(R, u1, u2) { + return this.mul(u1, false).add(R.mul(u2, false)).ok(); // Unsafe: do NOT use for stuff related + } // to private keys. Doesn't use Shamir trick + toAffine() { + const { px: x, py: y, pz: z } = this; // (x, y, z) ∋ (x=x/z, y=y/z) + if (this.equals(I)) + return { x: 0n, y: 0n }; // fast-path for zero point + if (z === 1n) + return { x, y }; // if z is 1, pass affine coordinates as-is + const iz = inv(z); // z^-1: invert z + if (mod(z * iz) !== 1n) + err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math + return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1 + } + assertValidity() { + const { x, y } = this.aff(); // convert to 2d xy affine point. + if (!fe(x) || !fe(y)) + err('Point invalid: x or y'); // x and y must be in range 0 < n < P + return mod(y * y) === crv(x) ? // y² = x³ + ax + b, must be equal + this : err('Point invalid: not on curve'); + } + multiply(n) { return this.mul(n); } // Aliases to compress code + aff() { return this.toAffine(); } + ok() { return this.assertValidity(); } + toHex(isCompressed = true) { + const { x, y } = this.aff(); // convert to 2d xy affine point + const head = isCompressed ? ((y & 1n) === 0n ? '02' : '03') : '04'; // 0x02, 0x03, 0x04 prefix + return head + n2h(x) + (isCompressed ? '' : n2h(y)); // prefix||x and ||y + } + toRawBytes(isCompressed = true) { + return h2b(this.toHex(isCompressed)); // re-use toHex(), convert hex to bytes + } +} +Point.BASE = new Point(Gx, Gy, 1n); // Generator / base point +Point.ZERO = new Point(0n, 1n, 0n); // Identity / zero point +const { BASE: G, ZERO: I } = Point; // Generator, identity points +const padh = (n, pad) => n.toString(16).padStart(pad, '0'); +const b2h = (b) => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex +const h2b = (hex) => { + const l = hex.length; // error if not string, + if (!str(hex) || l % 2) + err('hex invalid 1'); // or has odd length like 3, 5. + const arr = u8n(l / 2); // create result array + for (let i = 0; i < arr.length; i++) { + const j = i * 2; + const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr + const b = Number.parseInt(h, 16); // byte, created from string part + if (Number.isNaN(b) || b < 0) + err('hex invalid 2'); // byte must be valid 0 <= byte < 256 + arr[i] = b; + } + return arr; +}; +const b2n = (b) => BigInt('0x' + (b2h(b) || '0')); // bytes to number +const slcNum = (b, from, to) => b2n(b.slice(from, to)); // slice bytes num +const n2b = (num) => { + return big(num) && num >= 0n && num < B256 ? h2b(padh(num, 2 * fLen)) : err('bigint expected'); +}; +const n2h = (num) => b2h(n2b(num)); // number to 32b hex +const concatB = (...arrs) => { + const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length + let pad = 0; // walk through each array, + arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type + return r; +}; +const inv = (num, md = P) => { + if (num === 0n || md <= 0n) + err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now + let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n; + while (a !== 0n) { // uses euclidean gcd algorithm + const q = b / a, r = b % a; // not constant-time + const m = x - u * q, n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point +}; +const sqrt = (n) => { + let r = 1n; // So, a special, fast case. Paper: "Square Roots from 1;24,51,10 to Dan Shanks". + for (let num = n, e = (P + 1n) / 4n; e > 0n; e >>= 1n) { // powMod: modular exponentiation. + if (e & 1n) + r = (r * num) % P; // Uses exponentiation by squaring. + num = (num * num) % P; // Not constant-time. + } + return mod(r * r) === n ? r : err('sqrt invalid'); // check if result is valid +}; +const toPriv = (p) => { + if (!big(p)) + p = b2n(toU8(p, fLen)); // convert to bigint when bytes + return ge(p) ? p : err('private key out of range'); // check if bigint is in range +}; +const moreThanHalfN = (n) => n > (N >> 1n); // if a number is bigger than CURVE.n/2 +const getPublicKey = (privKey, isCompressed = true) => { + return Point.fromPrivateKey(privKey).toRawBytes(isCompressed); // 33b or 65b output +}; +class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); // recovery bit is optional when + } // constructed outside. + static fromCompact(hex) { + hex = toU8(hex, 64); // compact repr is (32b r)||(32b s) + return new Signature(slcNum(hex, 0, fLen), slcNum(hex, fLen, 2 * fLen)); + } + assertValidity() { return ge(this.r) && ge(this.s) ? this : err(); } // 0 < r or s < CURVE.n + addRecoveryBit(rec) { + return new Signature(this.r, this.s, rec); + } + hasHighS() { return moreThanHalfN(this.s); } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, mod(this.s, N), this.recovery) : this; + } + recoverPublicKey(msgh) { + const { r, s, recovery: rec } = this; // secg.org/sec1-v2.pdf 4.1.6 + if (![0, 1, 2, 3].includes(rec)) + err('recovery id invalid'); // check recovery id + const h = bits2int_modN(toU8(msgh, fLen)); // Truncate hash + const radj = rec === 2 || rec === 3 ? r + N : r; // If rec was 2 or 3, q.x is bigger than n + if (radj >= P) + err('q.x invalid'); // ensure q.x is still a field element + const head = (rec & 1) === 0 ? '02' : '03'; // head is 0x02 or 0x03 + const R = Point.fromHex(head + n2h(radj)); // concat head + hex repr of r + const ir = inv(radj, N); // r^-1 + const u1 = mod(-h * ir, N); // -hr^-1 + const u2 = mod(s * ir, N); // sr^-1 + return G.mulAddQUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + } + toCompactRawBytes() { return h2b(this.toCompactHex()); } // Uint8Array 64b compact repr + toCompactHex() { return n2h(this.r) + n2h(this.s); } // hex 64b compact repr +} +const bits2int = (bytes) => { + const delta = bytes.length * 8 - 256; // RFC suggests optional truncating via bits2octets + const num = b2n(bytes); // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which + return delta > 0 ? num >> BigInt(delta) : num; // matches bits2int. bits2int can produce res>N. +}; +const bits2int_modN = (bytes) => { + return mod(bits2int(bytes), N); // with 0: BAD for trunc as per RFC vectors +}; +const i2o = (num) => n2b(num); // int to octets +const cr = () => // We support: 1) browsers 2) node.js 19+ 3) deno, other envs with crypto + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +let _hmacSync; // Can be redefined by use in utils; built-ins don't provide it +const optS = { lowS: true }; // opts for sign() +const optV = { lowS: true }; // standard opts for verify() +const prepSig = (msgh, priv, opts = optS) => { + if (['der', 'recovered', 'canonical'].some(k => k in opts)) // Ban legacy options + err('sign() legacy options not supported'); + let { lowS } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A + const h1i = bits2int_modN(toU8(msgh)); // msg bigint + const h1o = i2o(h1i); // msg octets + const d = toPriv(priv); // validate private key, convert to bigint + const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2 + let ent = opts.extraEntropy; // RFC6979 3.6: additional k' (optional) + if (ent) { // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + if (ent === true) + ent = etc.randomBytes(fLen); // if true, use CSPRNG to generate data + const e = toU8(ent); // convert Hex|Bytes to Bytes + if (e.length !== fLen) + err(); // Expected 32 bytes of extra data + seed.push(e); + } + const m = h1i; // convert msg to bigint + const k2sig = (kBytes) => { + const k = bits2int(kBytes); // RFC6979 method. + if (!ge(k)) + return; // Check 0 < k < CURVE.n + const ik = inv(k, N); // k^-1 mod n, NOT mod P + const q = G.mul(k).aff(); // q = Gk + const r = mod(q.x, N); // r = q.x mod n + if (r === 0n) + return; // r=0 invalid + const s = mod(ik * mod(m + mod(d * r, N), N), N); // s = k^-1(m + rd) mod n + if (s === 0n) + return; // s=0 invalid + let normS = s; // normalized S + let rec = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit + if (lowS && moreThanHalfN(s)) { // if lowS was passed, ensure s is always + normS = mod(-s, N); // in the bottom half of CURVE.n + rec ^= 1; + } + return new Signature(r, normS, rec); // use normS, not s + }; + return { seed: concatB(...seed), k2sig }; +}; +function hmacDrbg(asynchronous) { + let v = u8n(fLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(fLen); // Steps B, 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 _e = 'drbg: tried 1000 values'; + if (asynchronous) { // asynchronous=true + const h = (...b) => etc.hmacSha256Async(k, v, ...b); // hmac(k)(v, ...values) + const reseed = async (seed = u8n()) => { + k = await h(u8n([0x00]), seed); // k = hmac(K || V || 0x00 || seed) + v = await h(); // v = hmac(K || V) + if (seed.length === 0) + return; + k = await h(u8n([0x01]), seed); // k = hmac(K || V || 0x01 || seed) + v = await h(); // v = hmac(K || V) + }; + const gen = async () => { + if (i++ >= 1000) + err(_e); + v = await h(); // v = hmac(K || V) + return v; + }; + return async (seed, pred) => { + reset(); // the returned fn, don't, it's: 1. slower (JIT). 2. unsafe (async race conditions) + await reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(await gen()))) + await reseed(); // test predicate until it returns ok + reset(); + return res; + }; + } + else { + const h = (...b) => { + const f = _hmacSync; + if (!f) + err('etc.hmacSha256Sync not set'); + return f(k, v, ...b); // hmac(k)(v, ...values) + }; + const reseed = (seed = u8n()) => { + k = h(u8n([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8n([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + if (i++ >= 1000) + err(_e); + v = h(); // v = hmac(k || v) + return v; + }; + return (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(); // test predicate until it returns ok + reset(); + return res; + }; + } +} +// ECDSA signature generation. via secg.org/sec1-v2.pdf 4.1.2 + RFC6979 deterministic k +const signAsync = async (msgh, priv, opts = optS) => { + const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg + return hmacDrbg(true)(seed, k2sig); // Re-run drbg until k2sig returns ok +}; +const sign = (msgh, priv, opts = optS) => { + const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg + return hmacDrbg(false)(seed, k2sig); // Re-run drbg until k2sig returns ok +}; +const verify = (sig, msgh, pub, opts = optV) => { + let { lowS } = opts; // ECDSA signature verification + if (lowS == null) + lowS = true; // Default lowS=true + if ('strict' in opts) + err('verify() legacy options not supported'); // legacy param + let sig_, h, P; // secg.org/sec1-v2.pdf 4.1.4 + const rs = sig && typeof sig === 'object' && 'r' in sig; // Previous ver supported DER sigs. We + if (!rs && (toU8(sig).length !== 2 * fLen)) // throw error when DER is suspected now. + err('signature must be 64 bytes'); + try { + sig_ = rs ? new Signature(sig.r, sig.s).assertValidity() : Signature.fromCompact(sig); + h = bits2int_modN(toU8(msgh)); // Truncate hash + P = pub instanceof Point ? pub.ok() : Point.fromHex(pub); // Validate public key + } + catch (e) { + return false; + } // Check sig for validity in both cases + if (!sig_) + return false; + const { r, s } = sig_; + if (lowS && moreThanHalfN(s)) + return false; // lowS bans sig.s >= CURVE.n/2 + let R; + try { + const is = inv(s, N); // s^-1 + const u1 = mod(h * is, N); // u1 = hs^-1 mod n + const u2 = mod(r * is, N); // u2 = rs^-1 mod n + R = G.mulAddQUns(P, u1, u2).aff(); // R = u1⋅G + u2⋅P + } + catch (error) { + return false; + } + if (!R) + return false; // stop if R is identity / zero point + const v = mod(R.x, N); // R.x must be in N's field, not P's + return v === r; // mod(R.x, n) == r +}; +const getSharedSecret = (privA, pubB, isCompressed = true) => { + return Point.fromHex(pubB).mul(toPriv(privA)).toRawBytes(isCompressed); // ECDH +}; +const hashToPrivateKey = (hash) => { + hash = toU8(hash); // produces private keys with modulo bias + const minLen = fLen + 8; // being neglible. + if (hash.length < minLen || hash.length > 1024) + err('expected proper params'); + const num = mod(b2n(hash), N - 1n) + 1n; // takes at least n+8 bytes + return n2b(num); +}; +const etc = { + hexToBytes: h2b, bytesToHex: b2h, // share API with noble-curves. + concatBytes: concatB, bytesToNumberBE: b2n, numberToBytesBE: n2b, + mod, invert: inv, // math utilities + hmacSha256Async: async (key, ...msgs) => { + const c = cr(); // async HMAC-SHA256, no sync built-in! + const s = c && c.subtle; // For React Native support, see README. + if (!s) + return err('etc.hmacSha256Async not set'); // Uses webcrypto built-in cryptography. + const k = await s.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']); + return u8n(await s.sign('HMAC', k, concatB(...msgs))); + }, + hmacSha256Sync: _hmacSync, // For TypeScript. Actual logic is below + hashToPrivateKey, + randomBytes: (len = 32) => { + const crypto = cr(); // Must be shimmed in node.js <= 18 to prevent error. See README. + if (!crypto || !crypto.getRandomValues) + err('crypto.getRandomValues must be defined'); + return crypto.getRandomValues(u8n(len)); + }, +}; +const utils = { + normPrivateKeyToScalar: toPriv, + isValidPrivateKey: (key) => { try { + return !!toPriv(key); + } + catch (e) { + return false; + } }, + randomPrivateKey: () => hashToPrivateKey(etc.randomBytes(fLen + 16)), // FIPS 186 B.4.1. + precompute(w = 8, p = G) { p.multiply(3n); w; return p; }, // no-op +}; +Object.defineProperties(etc, { hmacSha256Sync: { + configurable: false, get() { return _hmacSync; }, set(f) { if (!_hmacSync) + _hmacSync = f; }, + } }); +const W = 8; // Precomputes-related code. W = window size +const precompute = () => { + const points = []; // 10x sign(), 2x verify(). To achieve this, + const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate + let p = G, b = p; // a lot of points related to base point G. + for (let w = 0; w < windows; w++) { // Points are stored in array and used + b = p; // any time Gx multiplication is done. + points.push(b); // They consume 16-32 MiB of RAM. + for (let i = 1; i < 2 ** (W - 1); i++) { + b = b.add(p); + points.push(b); + } + p = b.double(); // Precomputes don't speed-up getSharedKey, + } // which multiplies user point by scalar, + return points; // when precomputes are using base point +}; +let Gpows = undefined; // precomputes for base point G +const wNAF = (n) => { + // Compared to other point mult methods, + const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction + const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate + let p = I, f = G; // f must be G, or could become I in the end + const windows = 1 + 256 / W; // W=8 17 windows + const wsize = 2 ** (W - 1); // W=8 128 window size + const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111 + const maxNum = 2 ** W; // W=8 256 + const shiftBy = BigInt(W); // W=8 8 + for (let w = 0; w < windows; w++) { + const off = w * wsize; + let wbits = Number(n & mask); // extract W bits. + n >>= shiftBy; // shift number by W bits. + if (wbits > wsize) { + wbits -= maxNum; + n += 1n; + } // split if bits > max: +224 => 256-32 + const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both + const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both + if (wbits === 0) { + f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point + } + else { // ^ can't add off2, off2 = I + p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point + } + } + return { p, f }; // return both real and fake points for JIT +}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul() +export { getPublicKey, sign, signAsync, verify, CURVE, // Remove the export to easily use in REPL +getSharedSecret, etc, utils, Point as ProjectivePoint, Signature }; // envs like browser console diff --git a/src/libMPC/node_modules/@noble/secp256k1/index.ts b/src/libMPC/node_modules/@noble/secp256k1/index.ts new file mode 100644 index 0000000..b2d6cd3 --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/index.ts @@ -0,0 +1,441 @@ +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +const B256 = 2n ** 256n; // secp256k1 is short weierstrass curve +const P = B256 - 0x1000003d1n; // curve's field prime +const N = B256 - 0x14551231950b75fc4402da1732fc9bebfn; // curve (group) order +const Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n; // base point x +const Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n; // base point y +const CURVE = {p: P, n: N, a: 0n, b: 7n, Gx, Gy}; // exported variables incl. a, b +const fLen = 32; // field / group byte length +type Bytes = Uint8Array; type Hex = Bytes | string; type PrivKey = Hex | bigint; +const crv = (x: bigint) => mod(mod(x * x) * x + CURVE.b); // x³ + ax + b weierstrass formula; a=0 +const err = (m = ''): never => { throw new Error(m); }; // error helper, messes-up stack trace +const big = (n: unknown): n is bigint => typeof n === 'bigint'; // is big integer +const str = (s: unknown): s is string => typeof s === 'string'; // is string +const fe = (n: bigint) => big(n) && 0n < n && n < P; // is field element (invertible) +const ge = (n: bigint) => big(n) && 0n < n && n < N; // is group element +const isu8 = (a: unknown): a is Uint8Array => ( + a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array') +); +const au8 = (a: unknown, l?: number): Bytes => // assert is Uint8Array (of specific length) + !isu8(a) || (typeof l === 'number' && l > 0 && a.length !== l) ? + err('Uint8Array expected') : a; +const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array +const toU8 = (a: Hex, len?: number) => au8(str(a) ? h2b(a) : u8n(au8(a)), len); // norm(hex/u8a) to u8a +const mod = (a: bigint, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division +const isPoint = (p: unknown) => (p instanceof Point ? p : err('Point expected')); // is 3d point +interface AffinePoint { x: bigint, y: bigint } // Point in 2d xy affine coordinates +class Point { // Point in 3d xyz projective coordinates + constructor(readonly px: bigint, readonly py: bigint, readonly pz: bigint) {} //3d=less inversions + static readonly BASE = new Point(Gx, Gy, 1n); // Generator / base point + static readonly ZERO = new Point(0n, 1n, 0n); // Identity / zero point + static fromAffine (p: AffinePoint) { // (0, 0) => (0, 1, 0), not (0, 0, 1) + return ((p.x === 0n) && (p.y === 0n)) ? Point.ZERO : new Point(p.x, p.y, 1n); + } + static fromHex(hex: Hex): Point { // Convert Uint8Array or hex string to Point + hex = toU8(hex); // convert hex string to Uint8Array + let p: Point | undefined = undefined; + const head = hex[0], tail = hex.subarray(1); // first byte is prefix, rest is data + const x = slcNum(tail, 0, fLen), len = hex.length; // next 32 bytes are x coordinate + if (len === 33 && [0x02, 0x03].includes(head)) { // compressed points: 33b, start + if (!fe(x)) err('Point hex invalid: x not FE'); // with byte 0x02 or 0x03. Check if 0 0n; d = d.double(), n >>= 1n) { // double-and-add ladder + if (n & 1n) p = p.add(d); // if bit is present, add to point + else if (safe) f = f.add(d); // if not, add to fake for timing safety + } + return p; + } + mulAddQUns(R: Point, u1: bigint, u2: bigint) { // Double scalar mult. Q = u1⋅G + u2⋅R. + return this.mul(u1, false).add(R.mul(u2, false)).ok(); // Unsafe: do NOT use for stuff related + } // to private keys. Doesn't use Shamir trick + toAffine(): AffinePoint { // Convert point to 2d xy affine point. + const { px: x, py: y, pz: z } = this; // (x, y, z) ∋ (x=x/z, y=y/z) + if (this.equals(I)) return { x: 0n, y: 0n }; // fast-path for zero point + if (z === 1n) return { x, y }; // if z is 1, pass affine coordinates as-is + const iz = inv(z); // z^-1: invert z + if (mod(z * iz) !== 1n) err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math + return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1 + } + assertValidity(): Point { // Checks if the point is valid and on-curve + const { x, y } = this.aff(); // convert to 2d xy affine point. + if (!fe(x) || !fe(y)) err('Point invalid: x or y'); // x and y must be in range 0 < n < P + return mod(y * y) === crv(x) ? // y² = x³ + ax + b, must be equal + this : err('Point invalid: not on curve'); + } + multiply(n: bigint) { return this.mul(n); } // Aliases to compress code + aff() { return this.toAffine(); } + ok() { return this.assertValidity(); } + toHex(isCompressed = true) { // Encode point to hex string. + const { x, y } = this.aff(); // convert to 2d xy affine point + const head = isCompressed ? ((y & 1n) === 0n ? '02' : '03') : '04'; // 0x02, 0x03, 0x04 prefix + return head + n2h(x) + (isCompressed ? '' : n2h(y));// prefix||x and ||y + } + toRawBytes(isCompressed = true) { // Encode point to Uint8Array. + return h2b(this.toHex(isCompressed)); // re-use toHex(), convert hex to bytes + } +} +const { BASE: G, ZERO: I } = Point; // Generator, identity points +const padh = (n: number | bigint, pad: number) => n.toString(16).padStart(pad, '0'); +const b2h = (b: Bytes): string => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex +const h2b = (hex: string): Bytes => { // hex to bytes + const l = hex.length; // error if not string, + if (!str(hex) || l % 2) err('hex invalid 1'); // or has odd length like 3, 5. + const arr = u8n(l / 2); // create result array + for (let i = 0; i < arr.length; i++) { + const j = i * 2; + const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr + const b = Number.parseInt(h, 16); // byte, created from string part + if (Number.isNaN(b) || b < 0) err('hex invalid 2'); // byte must be valid 0 <= byte < 256 + arr[i] = b; + } + return arr; +}; +const b2n = (b: Bytes): bigint => BigInt('0x' + (b2h(b) || '0')); // bytes to number +const slcNum = (b: Bytes, from: number, to: number) => b2n(b.slice(from, to)); // slice bytes num +const n2b = (num: bigint): Bytes => { // number to 32b. Must be 0 <= num < B256 + return big(num) && num >= 0n && num < B256 ? h2b(padh(num, 2 * fLen)) : err('bigint expected'); +}; +const n2h = (num: bigint): string => b2h(n2b(num)); // number to 32b hex +const concatB = (...arrs: Bytes[]) => { // concatenate Uint8Array-s + const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length + let pad = 0; // walk through each array, + arrs.forEach(a => {r.set(a, pad); pad += a.length}); // ensure they have proper type + return r; +}; +const inv = (num: bigint, md = P): bigint => { // modular inversion + if (num === 0n || md <= 0n) err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now + let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n; + while (a !== 0n) { // uses euclidean gcd algorithm + const q = b / a, r = b % a; // not constant-time + const m = x - u * q, n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point +}; +const sqrt = (n: bigint) => { // √n = n^((p+1)/4) for fields p = 3 mod 4 + let r = 1n; // So, a special, fast case. Paper: "Square Roots from 1;24,51,10 to Dan Shanks". + for (let num = n, e = (P + 1n) / 4n; e > 0n; e >>= 1n) { // powMod: modular exponentiation. + if (e & 1n) r = (r * num) % P; // Uses exponentiation by squaring. + num = (num * num) % P; // Not constant-time. + } + return mod(r * r) === n ? r : err('sqrt invalid'); // check if result is valid +}; +const toPriv = (p: PrivKey): bigint => { // normalize private key to bigint + if (!big(p)) p = b2n(toU8(p, fLen)); // convert to bigint when bytes + return ge(p) ? p : err('private key out of range'); // check if bigint is in range +}; +const moreThanHalfN = (n: bigint): boolean => n > (N >> 1n); // if a number is bigger than CURVE.n/2 +const getPublicKey = (privKey: PrivKey, isCompressed = true) => { // Make public key from priv + return Point.fromPrivateKey(privKey).toRawBytes(isCompressed); // 33b or 65b output +} +type SignatureWithRecovery = Signature & { recovery: number } +class Signature { // ECDSA Signature class + constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) { + this.assertValidity(); // recovery bit is optional when + } // constructed outside. + static fromCompact(hex: Hex) { // create signature from 64b compact repr + hex = toU8(hex, 64); // compact repr is (32b r)||(32b s) + return new Signature(slcNum(hex, 0, fLen), slcNum(hex, fLen, 2 * fLen)); + } + assertValidity() { return ge(this.r) && ge(this.s) ? this : err(); } // 0 < r or s < CURVE.n + addRecoveryBit(rec: number): SignatureWithRecovery { + return new Signature(this.r, this.s, rec) as SignatureWithRecovery; + } + hasHighS() { return moreThanHalfN(this.s); } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, mod(this.s, N), this.recovery) : this + } + recoverPublicKey(msgh: Hex): Point { // ECDSA public key recovery + const { r, s, recovery: rec } = this; // secg.org/sec1-v2.pdf 4.1.6 + if (![0, 1, 2, 3].includes(rec!)) err('recovery id invalid'); // check recovery id + const h = bits2int_modN(toU8(msgh, fLen)); // Truncate hash + const radj = rec === 2 || rec === 3 ? r + N : r; // If rec was 2 or 3, q.x is bigger than n + if (radj >= P) err('q.x invalid'); // ensure q.x is still a field element + const head = (rec! & 1) === 0 ? '02' : '03'; // head is 0x02 or 0x03 + const R = Point.fromHex(head + n2h(radj)); // concat head + hex repr of r + const ir = inv(radj, N); // r^-1 + const u1 = mod(-h * ir, N); // -hr^-1 + const u2 = mod(s * ir, N); // sr^-1 + return G.mulAddQUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + } + toCompactRawBytes() { return h2b(this.toCompactHex()); } // Uint8Array 64b compact repr + toCompactHex() { return n2h(this.r) + n2h(this.s); } // hex 64b compact repr +} +const bits2int = (bytes: Uint8Array): bigint => { // RFC6979: ensure ECDSA msg is X bytes. + const delta = bytes.length * 8 - 256; // RFC suggests optional truncating via bits2octets + const num = b2n(bytes); // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which + return delta > 0 ? num >> BigInt(delta) : num; // matches bits2int. bits2int can produce res>N. +}; +const bits2int_modN = (bytes: Uint8Array): bigint => { // int2octets can't be used; pads small msgs + return mod(bits2int(bytes), N); // with 0: BAD for trunc as per RFC vectors +}; +const i2o = (num: bigint): Bytes => n2b(num); // int to octets +declare const globalThis: Record | undefined; // Typescript symbol present in browsers +const cr = () => // We support: 1) browsers 2) node.js 19+ 3) deno, other envs with crypto + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +type HmacFnSync = undefined | ((key: Bytes, ...msgs: Bytes[]) => Bytes); +let _hmacSync: HmacFnSync; // Can be redefined by use in utils; built-ins don't provide it +const optS: { lowS?: boolean; extraEntropy?: boolean | Hex; } = { lowS: true }; // opts for sign() +const optV: { lowS?: boolean } = { lowS: true }; // standard opts for verify() +type BC = { seed: Bytes, k2sig : (kb: Bytes) => SignatureWithRecovery | undefined }; // Bytes+predicate checker +const prepSig = (msgh: Hex, priv: PrivKey, opts=optS): BC => {// prepare for RFC6979 sig generation + if (['der', 'recovered', 'canonical'].some(k => k in opts)) // Ban legacy options + err('sign() legacy options not supported'); + let { lowS } = opts; // generates low-s sigs by default + if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A + const h1i = bits2int_modN(toU8(msgh)); // msg bigint + const h1o = i2o(h1i); // msg octets + const d = toPriv(priv); // validate private key, convert to bigint + const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2 + let ent = opts.extraEntropy; // RFC6979 3.6: additional k' (optional) + if (ent) { // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + if (ent === true) ent = etc.randomBytes(fLen); // if true, use CSPRNG to generate data + const e = toU8(ent); // convert Hex|Bytes to Bytes + if (e.length !== fLen) err(); // Expected 32 bytes of extra data + seed.push(e); + } + const m = h1i; // convert msg to bigint + const k2sig = (kBytes: Bytes): SignatureWithRecovery | undefined => { // Transform k => Signature. + const k = bits2int(kBytes); // RFC6979 method. + if (!ge(k)) return; // Check 0 < k < CURVE.n + const ik = inv(k, N); // k^-1 mod n, NOT mod P + const q = G.mul(k).aff(); // q = Gk + const r = mod(q.x, N); // r = q.x mod n + if (r === 0n) return; // r=0 invalid + const s = mod(ik * mod(m + mod(d * r, N), N), N); // s = k^-1(m + rd) mod n + if (s === 0n) return; // s=0 invalid + let normS = s; // normalized S + let rec = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit + if (lowS && moreThanHalfN(s)) { // if lowS was passed, ensure s is always + normS = mod(-s, N); // in the bottom half of CURVE.n + rec ^= 1; + } + return new Signature(r, normS, rec) as SignatureWithRecovery; // use normS, not s + }; + return { seed: concatB(...seed), k2sig } +} +type Pred = (v: Uint8Array) => T | undefined; +function hmacDrbg(asynchronous: true): (seed: Bytes, predicate: Pred) => Promise; +function hmacDrbg(asynchronous: false): (seed: Bytes, predicate: Pred) => T; +function hmacDrbg(asynchronous: boolean) { // HMAC-DRBG async + let v = u8n(fLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(fLen); // Steps B, 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 _e = 'drbg: tried 1000 values'; + if (asynchronous) { // asynchronous=true + const h = (...b: Bytes[]) => etc.hmacSha256Async(k, v, ...b); // hmac(k)(v, ...values) + const reseed = async (seed = u8n()) => { // HMAC-DRBG reseed() function. Steps D-G + k = await h(u8n([0x00]), seed); // k = hmac(K || V || 0x00 || seed) + v = await h(); // v = hmac(K || V) + if (seed.length === 0) return; + k = await h(u8n([0x01]), seed); // k = hmac(K || V || 0x01 || seed) + v = await h(); // v = hmac(K || V) + }; + const gen = async () => { // HMAC-DRBG generate() function + if (i++ >= 1000) err(_e); + v = await h(); // v = hmac(K || V) + return v; + }; + return async (seed: Bytes, pred: Pred): Promise => { // Even though it feels safe to reuse + reset(); // the returned fn, don't, it's: 1. slower (JIT). 2. unsafe (async race conditions) + await reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(await gen()))) await reseed();// test predicate until it returns ok + reset(); + return res!; + }; + } else { + const h = (...b: Bytes[]) => { // asynchronous=false; same, but synchronous + const f = _hmacSync; + if (!f) err('etc.hmacSha256Sync not set'); + return f!(k, v, ...b); // hmac(k)(v, ...values) + }; + const reseed = (seed = u8n()) => { // HMAC-DRBG reseed() function. Steps D-G + k = h(u8n([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(u8n([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { // HMAC-DRBG generate() function + if (i++ >= 1000) err(_e); + v = h(); // v = hmac(k || v) + return v; + }; + return (seed: Bytes, pred: Pred): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) reseed(); // test predicate until it returns ok + reset(); + return res!; + }; + } +} +// ECDSA signature generation. via secg.org/sec1-v2.pdf 4.1.2 + RFC6979 deterministic k +const signAsync = async (msgh: Hex, priv: PrivKey, opts = optS): Promise => { + const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg + return hmacDrbg(true)(seed, k2sig); // Re-run drbg until k2sig returns ok +} +const sign = (msgh: Hex, priv: PrivKey, opts = optS): SignatureWithRecovery => { + const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg + return hmacDrbg(false)(seed, k2sig); // Re-run drbg until k2sig returns ok +} +type SigLike = { r: bigint, s: bigint }; +const verify = (sig: Hex | SigLike, msgh: Hex, pub: Hex, opts = optV): boolean => { + let { lowS } = opts; // ECDSA signature verification + if (lowS == null) lowS = true; // Default lowS=true + if ('strict' in opts) err('verify() legacy options not supported'); // legacy param + let sig_: Signature, h: bigint, P: Point; // secg.org/sec1-v2.pdf 4.1.4 + const rs = sig && typeof sig === 'object' && 'r' in sig; // Previous ver supported DER sigs. We + if (!rs && (toU8(sig).length !== 2 * fLen)) // throw error when DER is suspected now. + err('signature must be 64 bytes'); + try { + sig_ = rs ? new Signature(sig.r, sig.s).assertValidity() : Signature.fromCompact(sig); + h = bits2int_modN(toU8(msgh)); // Truncate hash + P = pub instanceof Point ? pub.ok() : Point.fromHex(pub); // Validate public key + } catch (e) { return false; } // Check sig for validity in both cases + if (!sig_) return false; + const { r, s } = sig_; + if (lowS && moreThanHalfN(s)) return false; // lowS bans sig.s >= CURVE.n/2 + let R: AffinePoint; + try { + const is = inv(s, N); // s^-1 + const u1 = mod(h * is, N); // u1 = hs^-1 mod n + const u2 = mod(r * is, N); // u2 = rs^-1 mod n + R = G.mulAddQUns(P, u1, u2).aff(); // R = u1⋅G + u2⋅P + } catch (error) { return false; } + if (!R) return false; // stop if R is identity / zero point + const v = mod(R.x, N); // R.x must be in N's field, not P's + return v === r; // mod(R.x, n) == r +} +const getSharedSecret = (privA: Hex, pubB: Hex, isCompressed = true): Bytes => { + return Point.fromHex(pubB).mul(toPriv(privA)).toRawBytes(isCompressed); // ECDH +} +const hashToPrivateKey = (hash: Hex): Bytes => { // FIPS 186 B.4.1 compliant key generation + hash = toU8(hash); // produces private keys with modulo bias + const minLen = fLen + 8; // being neglible. + if (hash.length < minLen || hash.length > 1024) err('expected proper params'); + const num = mod(b2n(hash), N - 1n) + 1n; // takes at least n+8 bytes + return n2b(num); +} +const etc = { // Not placed in utils because they + hexToBytes: h2b, bytesToHex: b2h, // share API with noble-curves. + concatBytes: concatB, bytesToNumberBE: b2n, numberToBytesBE: n2b, + mod, invert: inv, // math utilities + hmacSha256Async: async (key: Bytes, ...msgs: Bytes[]): Promise => { + const c = cr(); // async HMAC-SHA256, no sync built-in! + const s = c && c.subtle; // For React Native support, see README. + if (!s) return err('etc.hmacSha256Async not set'); // Uses webcrypto built-in cryptography. + const k = await s.importKey('raw', key, {name:'HMAC',hash:{name:'SHA-256'}}, false, ['sign']); + return u8n(await s.sign('HMAC', k, concatB(...msgs))); + }, + hmacSha256Sync: _hmacSync, // For TypeScript. Actual logic is below + hashToPrivateKey, + randomBytes: (len = 32): Bytes => { // CSPRNG (random number generator) + const crypto = cr(); // Must be shimmed in node.js <= 18 to prevent error. See README. + if (!crypto || !crypto.getRandomValues) err('crypto.getRandomValues must be defined'); + return crypto.getRandomValues(u8n(len)); + }, +} +const utils = { // utilities + normPrivateKeyToScalar: toPriv, + isValidPrivateKey: (key: Hex) => { try { return !!toPriv(key); } catch (e) { return false; } }, + randomPrivateKey: (): Bytes => hashToPrivateKey(etc.randomBytes(fLen + 16)), // FIPS 186 B.4.1. + precompute(w=8, p: Point = G) { p.multiply(3n); w; return p; }, // no-op +}; +Object.defineProperties(etc, { hmacSha256Sync: { // Allow setting it once, ignore then + configurable: false, get() { return _hmacSync; }, set(f) { if (!_hmacSync) _hmacSync = f; }, +} }); +const W = 8; // Precomputes-related code. W = window size +const precompute = () => { // They give 12x faster getPublicKey(), + const points: Point[] = []; // 10x sign(), 2x verify(). To achieve this, + const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate + let p = G, b = p; // a lot of points related to base point G. + for (let w = 0; w < windows; w++) { // Points are stored in array and used + b = p; // any time Gx multiplication is done. + points.push(b); // They consume 16-32 MiB of RAM. + for (let i = 1; i < 2 ** (W - 1); i++) { b = b.add(p); points.push(b); } + p = b.double(); // Precomputes don't speed-up getSharedKey, + } // which multiplies user point by scalar, + return points; // when precomputes are using base point +} +let Gpows: Point[] | undefined = undefined; // precomputes for base point G +const wNAF = (n: bigint): { p: Point; f: Point } => { // w-ary non-adjacent form (wNAF) method. + // Compared to other point mult methods, + const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction + const neg = (cnd: boolean, p: Point) => { let n = p.negate(); return cnd ? n : p; } // negate + let p = I, f = G; // f must be G, or could become I in the end + const windows = 1 + 256 / W; // W=8 17 windows + const wsize = 2 ** (W - 1); // W=8 128 window size + const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111 + const maxNum = 2 ** W; // W=8 256 + const shiftBy = BigInt(W); // W=8 8 + for (let w = 0; w < windows; w++) { + const off = w * wsize; + let wbits = Number(n & mask); // extract W bits. + n >>= shiftBy; // shift number by W bits. + if (wbits > wsize) { wbits -= maxNum; n += 1n; } // split if bits > max: +224 => 256-32 + const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both + const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both + if (wbits === 0) { + f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point + } else { // ^ can't add off2, off2 = I + p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point + } + } + return { p, f } // return both real and fake points for JIT +}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul() +export { getPublicKey, sign, signAsync, verify, CURVE, // Remove the export to easily use in REPL + getSharedSecret, etc, utils, Point as ProjectivePoint, Signature } // envs like browser console diff --git a/src/libMPC/node_modules/@noble/secp256k1/package.json b/src/libMPC/node_modules/@noble/secp256k1/package.json new file mode 100644 index 0000000..4da3209 --- /dev/null +++ b/src/libMPC/node_modules/@noble/secp256k1/package.json @@ -0,0 +1,61 @@ +{ + "name": "@noble/secp256k1", + "version": "2.1.0", + "description": "Fastest 4KB JS implementation of secp256k1 ECDH & ECDSA signatures compliant with RFC6979", + "files": [ + "index.js", + "index.d.ts", + "index.ts" + ], + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "build": "tsc", + "build:min": "cd test/build; npm install; npm run terser", + "build:mingz": "npm run --silent build:min | gzip -c8", + "build:release": "npm run --silent build:min > test/build/noble-secp256k1.min.js; npm run --silent build:mingz > test/build/noble-secp256k1.min.js.gz", + "test": "node test/index.test.js", + "test:webcrypto": "node test/secp256k1.webcrypto.test.js", + "bench": "node test/benchmark.js", + "loc": "echo \"`npm run --silent build:min | wc -c` symbols `wc -l < index.ts` LOC, `npm run --silent build:mingz | wc -c`B gzipped\"" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-secp256k1.git" + }, + "license": "MIT", + "devDependencies": { + "@noble/hashes": "1.4.0", + "@paulmillr/jsbt": "0.1.0", + "fast-check": "3.0.0", + "micro-bmark": "0.3.0", + "micro-should": "0.4.0", + "typescript": "5.3.2" + }, + "keywords": [ + "secp256k1", + "rfc6979", + "signature", + "ecdsa", + "noble", + "cryptography", + "elliptic curve", + "ecc", + "curve", + "schnorr", + "bitcoin", + "ethereum" + ], + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + } + }, + "funding": "https://paulmillr.com/funding/" +} diff --git a/src/libMPC/node_modules/base-x/LICENSE.md b/src/libMPC/node_modules/base-x/LICENSE.md new file mode 100644 index 0000000..c5dca45 --- /dev/null +++ b/src/libMPC/node_modules/base-x/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2018 base-x contributors +Copyright (c) 2014-2018 The Bitcoin Core developers + +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. diff --git a/src/libMPC/node_modules/base-x/README.md b/src/libMPC/node_modules/base-x/README.md new file mode 100644 index 0000000..537f1b9 --- /dev/null +++ b/src/libMPC/node_modules/base-x/README.md @@ -0,0 +1,74 @@ +# base-x + +[![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) +[![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Fast base encoding / decoding of any given alphabet using bitcoin style leading +zero compression. + +**WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. + +## Example + +Base58 + +``` javascript +var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +import basex from 'base-x' +var bs58 = basex(BASE58) + +var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') + +console.log(decoded) +// => Uint8Array(33) [ +// 128, 237, 219, 220, 17, 104, 241, 218, +// 234, 219, 211, 228, 76, 30, 63, 143, +// 90, 40, 76, 32, 41, 247, 138, 210, +// 106, 249, 133, 131, 164, 153, 222, 91, +// 25 +// ] + +console.log(bs58.encode(decoded)) +// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr +``` + +### Alphabets + +See below for a list of commonly recognized alphabets, and their respective base. + +Base | Alphabet +------------- | ------------- +2 | `01` +8 | `01234567` +11 | `0123456789a` +16 | `0123456789abcdef` +32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` +32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) +36 | `0123456789abcdefghijklmnopqrstuvwxyz` +58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` +62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` +64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` +67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` + + +## How it works + +It encodes octet arrays by doing long divisions on all significant digits in the +array, creating a representation of that number in the new base. Then for every +leading zero in the input (not significant as a number) it will encode as a +single leader character. This is the first in the alphabet and will decode as 8 +bits. The other characters depend upon the base. For example, a base58 alphabet +packs roughly 5.858 bits per character. + +This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode +to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each +character. + +While unusual, this does mean that no padding is required and it works for bases +like 43. + + +## LICENSE [MIT](LICENSE) +A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. diff --git a/src/libMPC/node_modules/base-x/package.json b/src/libMPC/node_modules/base-x/package.json new file mode 100644 index 0000000..489df47 --- /dev/null +++ b/src/libMPC/node_modules/base-x/package.json @@ -0,0 +1,58 @@ +{ + "name": "base-x", + "version": "5.0.0", + "description": "Fast base encoding / decoding of any given alphabet", + "type": "module", + "keywords": [ + "base-x", + "base58", + "base62", + "base64", + "crypto", + "crytography", + "decode", + "decoding", + "encode", + "encoding" + ], + "homepage": "https://github.com/cryptocoinjs/base-x", + "bugs": { + "url": "https://github.com/cryptocoinjs/base-x/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "files": [ + "src" + ], + "main": "src/cjs/index.cjs", + "module": "src/esm/index.js", + "types": "src/cjs/index.d.ts", + "exports": { + ".": { + "require": "./src/cjs/index.cjs", + "import": "./src/esm/index.js", + "types": "./src/cjs/index.d.ts" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/cryptocoinjs/base-x.git" + }, + "scripts": { + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json; npm run standard -- --fix", + "clean": "rimraf src", + "postbuild": "find src/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\;", + "gitdiff": "npm run build && git diff --exit-code", + "prepublish": "npm run gitdiff", + "standard": "standard --ignore test", + "test": "npm run unit && npm run standard", + "unit": "tape test/*.js" + }, + "devDependencies": { + "@types/node": "12.0.10", + "rimraf": "^3.0.2", + "standard": "^17.1.0", + "tape": "^5.3.0", + "typescript": "^5.4.5" + } +} diff --git a/src/libMPC/node_modules/base-x/src/cjs/index.cjs b/src/libMPC/node_modules/base-x/src/cjs/index.cjs new file mode 100644 index 0000000..0124347 --- /dev/null +++ b/src/libMPC/node_modules/base-x/src/cjs/index.cjs @@ -0,0 +1,122 @@ +'use strict' +// 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. +Object.defineProperty(exports, '__esModule', { value: true }) +function base (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + const BASE_MAP = new Uint8Array(256) + for (let j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255 + } + for (let i = 0; i < ALPHABET.length; i++) { + const x = ALPHABET.charAt(i) + const xc = x.charCodeAt(0) + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i + } + const BASE = ALPHABET.length + const LEADER = ALPHABET.charAt(0) + const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up + const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up + function encode (source) { + // eslint-disable-next-line no-empty + 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. + let zeroes = 0 + let length = 0 + let pbegin = 0 + const pend = source.length + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++ + zeroes++ + } + // Allocate enough space in big-endian base58 representation. + const size = ((pend - pbegin) * iFACTOR + 1) >>> 0 + const b58 = new Uint8Array(size) + // Process the bytes. + while (pbegin !== pend) { + let carry = source[pbegin] + // Apply "b58 = b58 * 256 + ch". + let i = 0 + for (let 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. + let it2 = size - length + while (it2 !== size && b58[it2] === 0) { + it2++ + } + // Translate the result into a string. + let str = LEADER.repeat(zeroes) + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return new Uint8Array() } + let psz = 0 + // Skip and count leading '1's. + let zeroes = 0 + let length = 0 + while (source[psz] === LEADER) { + zeroes++ + psz++ + } + // Allocate enough space in big-endian base256 representation. + const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. + const b256 = new Uint8Array(size) + // Process the characters. + while (source[psz]) { + // Decode character + let carry = BASE_MAP[source.charCodeAt(psz)] + // Invalid character + if (carry === 255) { return } + let i = 0 + for (let 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 leading zeroes in b256. + let it4 = size - length + while (it4 !== size && b256[it4] === 0) { + it4++ + } + const vch = new Uint8Array(zeroes + (size - it4)) + let j = zeroes + while (it4 !== size) { + vch[j++] = b256[it4++] + } + return vch + } + function decode (string) { + const buffer = decodeUnsafe(string) + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode, + decodeUnsafe, + decode + } +} +exports.default = base diff --git a/src/libMPC/node_modules/base-x/src/cjs/index.d.ts b/src/libMPC/node_modules/base-x/src/cjs/index.d.ts new file mode 100644 index 0000000..4fd9617 --- /dev/null +++ b/src/libMPC/node_modules/base-x/src/cjs/index.d.ts @@ -0,0 +1,9 @@ +declare function base(ALPHABET: string): base.BaseConverter; +export default base; +declare namespace base { + interface BaseConverter { + encode(buffer: Uint8Array | number[]): string; + decodeUnsafe(string: string): Uint8Array | undefined; + decode(string: string): Uint8Array; + } +} diff --git a/src/libMPC/node_modules/base-x/src/esm/index.js b/src/libMPC/node_modules/base-x/src/esm/index.js new file mode 100644 index 0000000..ac60db8 --- /dev/null +++ b/src/libMPC/node_modules/base-x/src/esm/index.js @@ -0,0 +1,120 @@ +// 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. +function base (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + const BASE_MAP = new Uint8Array(256) + for (let j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255 + } + for (let i = 0; i < ALPHABET.length; i++) { + const x = ALPHABET.charAt(i) + const xc = x.charCodeAt(0) + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i + } + const BASE = ALPHABET.length + const LEADER = ALPHABET.charAt(0) + const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up + const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up + function encode (source) { + // eslint-disable-next-line no-empty + 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. + let zeroes = 0 + let length = 0 + let pbegin = 0 + const pend = source.length + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++ + zeroes++ + } + // Allocate enough space in big-endian base58 representation. + const size = ((pend - pbegin) * iFACTOR + 1) >>> 0 + const b58 = new Uint8Array(size) + // Process the bytes. + while (pbegin !== pend) { + let carry = source[pbegin] + // Apply "b58 = b58 * 256 + ch". + let i = 0 + for (let 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. + let it2 = size - length + while (it2 !== size && b58[it2] === 0) { + it2++ + } + // Translate the result into a string. + let str = LEADER.repeat(zeroes) + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return new Uint8Array() } + let psz = 0 + // Skip and count leading '1's. + let zeroes = 0 + let length = 0 + while (source[psz] === LEADER) { + zeroes++ + psz++ + } + // Allocate enough space in big-endian base256 representation. + const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. + const b256 = new Uint8Array(size) + // Process the characters. + while (source[psz]) { + // Decode character + let carry = BASE_MAP[source.charCodeAt(psz)] + // Invalid character + if (carry === 255) { return } + let i = 0 + for (let 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 leading zeroes in b256. + let it4 = size - length + while (it4 !== size && b256[it4] === 0) { + it4++ + } + const vch = new Uint8Array(zeroes + (size - it4)) + let j = zeroes + while (it4 !== size) { + vch[j++] = b256[it4++] + } + return vch + } + function decode (string) { + const buffer = decodeUnsafe(string) + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode, + decodeUnsafe, + decode + } +} +export default base diff --git a/src/libMPC/node_modules/bech32/LICENSE b/src/libMPC/node_modules/bech32/LICENSE new file mode 100644 index 0000000..8ae7d39 --- /dev/null +++ b/src/libMPC/node_modules/bech32/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2017 Pieter Wuille +Copyright (c) 2018 bitcoinjs 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. diff --git a/src/libMPC/node_modules/bech32/README.md b/src/libMPC/node_modules/bech32/README.md new file mode 100644 index 0000000..0a48026 --- /dev/null +++ b/src/libMPC/node_modules/bech32/README.md @@ -0,0 +1,42 @@ +# bech32 +[![build status](https://secure.travis-ci.org/bitcoinjs/bech32.png)](http://travis-ci.org/bitcoinjs/bech32) +[![Version](http://img.shields.io/npm/v/bech32.svg)](https://www.npmjs.org/package/bech32) + +A [BIP173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)/[BIP350](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki) compatible Bech32/Bech32m encoding/decoding library. + + +## Example +``` javascript +let { bech32, bech32m } = require('bech32') + +bech32.decode('abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw') +// => { +// prefix: 'abcdef', +// words: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31] +// } +bech32m.decode('abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx') +// => { +// prefix: 'abcdef', +// words: [31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0] +// } + +// toWords etc. are available on both bech32 and bech32m objects +let words = bech32.toWords(Buffer.from('foobar', 'utf8')) +bech32.encode('foo', words) +// => 'foo1vehk7cnpwgry9h96' +bech32m.encode('foo', words) +// => 'foo1vehk7cnpwgkc4mqc' +``` + + +### Advanced +BIP173 enforces a limitation of 90 characters, if extend the `LIMIT` parameter beyond this, be aware that the [effectiveness of checksum decreases as the length increases](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#checksum-design). + +It is highly recommended **NOT** exceed 1023 characters, as the module could only guarantee detecting 1 error. + + +## Credits +- [Peter Wuille](https://github.com/sipa/bech32) for the reference JavaScript implementation, and for authoring the Bech32 [BIP173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) and Bech32m [BIP350](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki). + + +## License [MIT](LICENSE) diff --git a/src/libMPC/node_modules/bech32/dist/index.d.ts b/src/libMPC/node_modules/bech32/dist/index.d.ts new file mode 100644 index 0000000..40e93f8 --- /dev/null +++ b/src/libMPC/node_modules/bech32/dist/index.d.ts @@ -0,0 +1,18 @@ +declare function toWords(bytes: ArrayLike): number[]; +declare function fromWordsUnsafe(words: ArrayLike): number[] | undefined; +declare function fromWords(words: ArrayLike): number[]; +export declare const bech32: BechLib; +export declare const bech32m: BechLib; +export interface Decoded { + prefix: string; + words: number[]; +} +export interface BechLib { + decodeUnsafe: (str: string, LIMIT?: number | undefined) => Decoded | undefined; + decode: (str: string, LIMIT?: number | undefined) => Decoded; + encode: (prefix: string, words: ArrayLike, LIMIT?: number | undefined) => string; + toWords: typeof toWords; + fromWordsUnsafe: typeof fromWordsUnsafe; + fromWords: typeof fromWords; +} +export {}; diff --git a/src/libMPC/node_modules/bech32/dist/index.js b/src/libMPC/node_modules/bech32/dist/index.js new file mode 100644 index 0000000..e0bb6d8 --- /dev/null +++ b/src/libMPC/node_modules/bech32/dist/index.js @@ -0,0 +1,170 @@ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bech32m = exports.bech32 = void 0; +const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; +const ALPHABET_MAP = {}; +for (let z = 0; z < ALPHABET.length; z++) { + const x = ALPHABET.charAt(z); + ALPHABET_MAP[x] = z; +} +function polymodStep(pre) { + const b = pre >> 25; + return (((pre & 0x1ffffff) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3)); +} +function prefixChk(prefix) { + let chk = 1; + for (let i = 0; i < prefix.length; ++i) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + return 'Invalid prefix (' + prefix + ')'; + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + for (let i = 0; i < prefix.length; ++i) { + const v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk; +} +function convert(data, inBits, outBits, pad) { + let value = 0; + let bits = 0; + const maxV = (1 << outBits) - 1; + const result = []; + for (let i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } + else { + if (bits >= inBits) + return 'Excess padding'; + if ((value << (outBits - bits)) & maxV) + return 'Non-zero padding'; + } + return result; +} +function toWords(bytes) { + return convert(bytes, 8, 5, true); +} +function fromWordsUnsafe(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; +} +function fromWords(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); +} +function getLibraryFromEncoding(encoding) { + let ENCODING_CONST; + if (encoding === 'bech32') { + ENCODING_CONST = 1; + } + else { + ENCODING_CONST = 0x2bc830a3; + } + function encode(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError('Exceeds length limit'); + prefix = prefix.toLowerCase(); + // determine chk mod + let chk = prefixChk(prefix); + if (typeof chk === 'string') + throw new Error(chk); + let result = prefix + '1'; + for (let i = 0; i < words.length; ++i) { + const x = words[i]; + if (x >> 5 !== 0) + throw new Error('Non 5-bit word'); + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + for (let i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= ENCODING_CONST; + for (let i = 0; i < 6; ++i) { + const v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + ' too short'; + if (str.length > LIMIT) + return 'Exceeds length limit'; + // don't allow mixed case + const lowered = str.toLowerCase(); + const uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return 'Mixed-case string ' + str; + str = lowered; + const split = str.lastIndexOf('1'); + if (split === -1) + return 'No separator character for ' + str; + if (split === 0) + return 'Missing prefix for ' + str; + const prefix = str.slice(0, split); + const wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return 'Data too short'; + let chk = prefixChk(prefix); + if (typeof chk === 'string') + return chk; + const words = []; + for (let i = 0; i < wordChars.length; ++i) { + const c = wordChars.charAt(i); + const v = ALPHABET_MAP[c]; + if (v === undefined) + return 'Unknown character ' + c; + chk = polymodStep(chk) ^ v; + // not in the checksum? + if (i + 6 >= wordChars.length) + continue; + words.push(v); + } + if (chk !== ENCODING_CONST) + return 'Invalid checksum for ' + str; + return { prefix, words }; + } + function decodeUnsafe(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === 'object') + return res; + } + function decode(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === 'object') + return res; + throw new Error(res); + } + return { + decodeUnsafe, + decode, + encode, + toWords, + fromWordsUnsafe, + fromWords, + }; +} +exports.bech32 = getLibraryFromEncoding('bech32'); +exports.bech32m = getLibraryFromEncoding('bech32m'); diff --git a/src/libMPC/node_modules/bech32/package.json b/src/libMPC/node_modules/bech32/package.json new file mode 100644 index 0000000..d0c70ff --- /dev/null +++ b/src/libMPC/node_modules/bech32/package.json @@ -0,0 +1,50 @@ +{ + "name": "bech32", + "version": "2.0.0", + "description": "Bech32 encoding / decoding", + "keywords": [ + "base32", + "bech32", + "bech32m", + "bitcoin", + "crypto", + "crytography", + "decode", + "decoding", + "encode", + "encoding" + ], + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist/index.js", + "dist/index.d.ts" + ], + "license": "MIT", + "devDependencies": { + "@types/node": "^14.0.14", + "@types/tape": "^4.13.0", + "nyc": "^15.0.0", + "prettier": "^2.0.5", + "rimraf": "^3.0.2", + "tap-dot": "*", + "tape": "^4.13.2", + "tslint": "^6.1.3", + "typescript": "^3.9.5" + }, + "repository": { + "url": "http://github.com/bitcoinjs/bech32", + "type": "git" + }, + "scripts": { + "build": "npm run clean && tsc -d", + "clean": "rimraf dist", + "coverage": "nyc -x dist/test/*.js --check-coverage --branches 90 --functions 90 tape dist/test/*.js", + "format": "npm run prettier -- --write", + "format:ci": "npm run prettier -- --check", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "tslint -p tsconfig.json -c tslint.json", + "prettier": "prettier --print-width 100 --single-quote --trailing-comma=all \"**/!(*.d).ts\"", + "test": "tape dist/test/*.js | tap-dot" + } +} diff --git a/src/libMPC/node_modules/bip174/LICENSE b/src/libMPC/node_modules/bip174/LICENSE new file mode 100644 index 0000000..fdbcde9 --- /dev/null +++ b/src/libMPC/node_modules/bip174/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jonathan Underwood and BitcoinJS team + +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. diff --git a/src/libMPC/node_modules/bip174/README.md b/src/libMPC/node_modules/bip174/README.md new file mode 100644 index 0000000..3cf2bcc --- /dev/null +++ b/src/libMPC/node_modules/bip174/README.md @@ -0,0 +1,109 @@ +# bip174 +[![Build Status](https://github.com/bitcoinjs/bip174/actions/workflows/main_ci.yml/badge.svg)](https://github.com/bitcoinjs/bip174/actions/workflows/main_ci.yml) +[![NPM](https://img.shields.io/npm/v/bip174.svg)](https://www.npmjs.org/package/bip174) + +[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) + +A [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki) compatible partial Transaction encoding library. + +## Bitcoin users, use bitcoinjs-lib's Psbt class. + +This library is separate as an attempt to separate Bitcoin specific logic from the encoding format. + +I apologize if this library is hard to use. Removing Bitcoin specific logic from "Partially Signed BITCOIN Transaction" format was kind of hard. + +## Responsibilities Covered + +1. Creator: You can create a new psbt and add inputs and outputs, then add extra info to the inputs using each individual method. + (Note: Psbt.fromTransaction can create a PSBT from a serialized transaction, but all scriptSigs and witnessStacks must be empty, + and the transaction should not have the segwit marker and flagbyte.) +2. Updater: You can add one of all types of the input and output information. Each function has strict type checking at runtime. +3. Combiner: using Psbt.combine(...Psbt[]), it will do a dumb merge gathering all the new key value pairs from the subsequent PSBTs into itself. The psbt calling `combine` has highest priority. + +## Responsibilities NOT Covered + +In order to keep this library as separate from Bitcoin logic as possible, This library will not implement the following responsibilities. But rather, down the road bitcoinjs-lib will adopt this class and extend it internally to allow for the following: + +1. Signer: This class has no way to sign. You may add a PartialSig object though. +2. Extractor: This class has minimal knowledge of Bitcoin transactions, so creating a full transaction from a PSBT must be done with a bitcoin aware extended class. +3. Input Finalizer: This class, again, has no knowledge of whether an input is finished. + +## Static methods and addInput / addOutput require an abstract Transaction object + +* Static methods: You must pass a `TransactionFromBuffer` typed function. See `ts_src/lib/interfaces.ts` for info on the `Transaction` interface and the `TransactionFromBuffer` function. +* addInput/addOutput methods: The constructor takes a `Transaction` abstract interface that has an addInput/addOutput method which will be called. + +## Example +```javascript +const { Psbt } = require('bip174') +const { PsbtTransaction , pTxFromBuffer } = require('./someImplementation') +// Psbt requires a Transaction interface to create an instance, as well as +// A function that turns a buffer into that interface. See Transaction and TransactionFromBuffer +// in ts_src/lib/interfaces.ts ... + +// See tests/utils/txTools file for an example of a simple Bitcoin Transaction. +// Also see BitcoinJS-lib for an extended class that uses the Transaction class internally. +// Anyone using this library for Bitcoin specifically should use bitcoinjs-lib + +// Your PsbtTransaction will have a toBuffer function to allow for serialization +const tx = pTxFromBuffer(someTransactionBuffer); +const psbt = new Psbt(tx) + +// OR + +// This will parse the PSBT, and use the function you pass to parse the Transaction part +// the function should throw if the scriptSig section is not empty +const psbt = Psbt.fromBuffer(somePsbtBuffer, pTxFromBuffer) + +psbt.addInput({ + hash: '865dce988413971fd812d0e81a3395ed916a87ea533e1a16c0f4e15df96fa7d4', + index: 3, +}) +psbt.addInput({ + hash: 'ff5dce988413971fd812d0e81a3395ed916a87ea533e1a16c0f4e15df96fa7d4', + index: 1, +}) +psbt.addOutput({ + script: Buffer.from( + 'a914e18870f2c297fbfca54c5c6f645c7745a5b66eda87', + 'hex', + ), + value: 1234567890, +}) +psbt.addOutput({ + script: Buffer.from( + 'a914e18870f2c297fbfca54c5c6f645c7745a5b66eda87', + 'hex', + ), + value: 987654321, +}) +psbt.addRedeemScriptToInput(0, Buffer.from( + '00208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903', + 'hex', +)) +psbt.addWitnessScriptToInput(0, Buffer.from( + '522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b9903' + + '0b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e861519268' + + '60221f0e7352ae', + 'hex', +)) +psbt.addBip32DerivationToInput(0, { + masterFingerprint: Buffer.from('d90c6a4f', 'hex'), + pubkey: Buffer.from( + '023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e73', + 'hex', + ), + path: "m/0'/0'/3'", +}) +psbt.addBip32DerivationToInput(0, { + masterFingerprint: Buffer.from('d90c6a4f', 'hex'), + pubkey: Buffer.from( + '03089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc', + 'hex', + ), + path: "m/0'/0'/2'", +}) +const b64 = psbt.toBase64(); +``` + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/bip174/package.json b/src/libMPC/node_modules/bip174/package.json new file mode 100644 index 0000000..e7cb221 --- /dev/null +++ b/src/libMPC/node_modules/bip174/package.json @@ -0,0 +1,65 @@ +{ + "name": "bip174", + "version": "3.0.0-rc.1", + "description": "", + "main": "src/cjs/lib/psbt.cjs", + "module": "src/esm/lib/psbt.js", + "types": "src/esm/lib/psbt.d.ts", + "exports": { + ".": { + "types": "./src/esm/lib/psbt.d.ts", + "import": "./src/esm/lib/psbt.js", + "require": "./src/cjs/lib/psbt.cjs" + } + }, + "type": "module", + "files": [ + "src/cjs/lib", + "src/esm/lib" + ], + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json && npm run formatjs", + "checkHybrid": "chmod +x test.cjs && node test.cjs", + "clean": "rimraf src types", + "coverage": "c8 --check-coverage --include='src/esm/lib/**/*.js' --reporter=lcov --reporter=text --branches 90 --functions 90 --lines 90 npm run unit", + "flb": "npm run format && npm run lint && npm run build", + "format": "npm run prettier -- --write", + "formatjs": "npm run prettierjs -- --write > /dev/null 2>&1", + "format:ci": "npm run prettier -- --check && npm run prettierjs -- --check", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "tslint -p tsconfig.json -c tslint.json", + "postbuild": "find src/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\; && chmod +x fixup.cjs && node fixup.cjs", + "prettier": "prettier 'ts_src/**/*.ts' --ignore-path ./.prettierignore", + "prettierjs": "prettier 'src/**/*.js' --ignore-path ./.prettierignore", + "test": "npm run format:ci && npm run lint && npm run build && npm run coverage", + "unit": "tape src/esm/tests/*.js src/esm/tests/fromBIP/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/bitcoinjs/bip174.git" + }, + "dependencies": { + "uint8array-tools": "^0.0.9", + "varuint-bitcoin": "^2.0.0" + }, + "devDependencies": { + "@types/node": "12.0.8", + "@types/tape": "4.2.33", + "bitcoinjs-lib": "^6.1.6", + "c8": "^10.1.2", + "prettier": "^1.18.2", + "rimraf": "^2.6.3", + "tape": "^5.3.0", + "tslint": "5.17.0", + "typescript": "3.5.2" + }, + "author": "Jonathan Underwood", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitcoinjs/bip174/issues" + }, + "homepage": "https://github.com/bitcoinjs/bip174#readme" +} diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/combiner/index.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/combiner/index.cjs new file mode 100644 index 0000000..6ce2fdd --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/combiner/index.cjs @@ -0,0 +1,95 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const index_js_1 = require('../parser/index.cjs'); +const tools = __importStar(require('uint8array-tools')); +function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = index_js_1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + tools.compare(otherTx.toBuffer(), selfTx.toBuffer()) !== 0 + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = index_js_1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return index_js_1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); +} +exports.combine = combine; +function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => tools.toHex(kv.key) === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; +} +function getTx(psbt) { + return psbt.globalMap.unsignedTx; +} +function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = tools.toHex(keyVal.key); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; +} diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/globalXpub.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/globalXpub.cjs new file mode 100644 index 0000000..18449b7 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/globalXpub.cjs @@ -0,0 +1,96 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +const range = n => [...Array(n).keys()]; +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = tools.readUInt32(keyVal.value, i * 4 + 4, 'LE'); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; +} +exports.decode = decode; +function encode(data) { + const head = new Uint8Array([typeFields_js_1.GlobalTypes.GLOBAL_XPUB]); + const key = tools.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = new Uint8Array(splitPath.length * 4); + value.set(data.masterFingerprint, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + tools.writeUInt32(value, offset, num, 'LE'); + offset += 4; + }); + return { + key, + value, + }; +} +exports.encode = encode; +exports.expected = + '{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }'; +function check(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + epk instanceof Uint8Array && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + mfp instanceof Uint8Array && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)*$/) + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.extendedPubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.extendedPubkey, item.extendedPubkey)) + .length === 0 + ); +} +exports.canAddToArray = canAddToArray; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/unsignedTx.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/unsignedTx.cjs new file mode 100644 index 0000000..6822620 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/global/unsignedTx.cjs @@ -0,0 +1,10 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +function encode(data) { + return { + key: new Uint8Array([typeFields_js_1.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; +} +exports.encode = encode; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/index.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/index.cjs new file mode 100644 index 0000000..f94d2ad --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/index.cjs @@ -0,0 +1,100 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../typeFields.cjs'); +const globalXpub = __importStar(require('./global/globalXpub.cjs')); +const unsignedTx = __importStar(require('./global/unsignedTx.cjs')); +const finalScriptSig = __importStar(require('./input/finalScriptSig.cjs')); +const finalScriptWitness = __importStar( + require('./input/finalScriptWitness.cjs'), +); +const nonWitnessUtxo = __importStar(require('./input/nonWitnessUtxo.cjs')); +const partialSig = __importStar(require('./input/partialSig.cjs')); +const porCommitment = __importStar(require('./input/porCommitment.cjs')); +const sighashType = __importStar(require('./input/sighashType.cjs')); +const tapKeySig = __importStar(require('./input/tapKeySig.cjs')); +const tapLeafScript = __importStar(require('./input/tapLeafScript.cjs')); +const tapMerkleRoot = __importStar(require('./input/tapMerkleRoot.cjs')); +const tapScriptSig = __importStar(require('./input/tapScriptSig.cjs')); +const witnessUtxo = __importStar(require('./input/witnessUtxo.cjs')); +const tapTree = __importStar(require('./output/tapTree.cjs')); +const bip32Derivation = __importStar(require('./shared/bip32Derivation.cjs')); +const checkPubkey = __importStar(require('./shared/checkPubkey.cjs')); +const redeemScript = __importStar(require('./shared/redeemScript.cjs')); +const tapBip32Derivation = __importStar( + require('./shared/tapBip32Derivation.cjs'), +); +const tapInternalKey = __importStar(require('./shared/tapInternalKey.cjs')); +const witnessScript = __importStar(require('./shared/witnessScript.cjs')); +const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), +}; +exports.globals = globals; +const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_js_1.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_js_1.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_js_1.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_js_1.InputTypes.PARTIAL_SIG, + typeFields_js_1.InputTypes.BIP32_DERIVATION, + ]), + tapKeySig, + tapScriptSig, + tapLeafScript, + tapBip32Derivation: tapBip32Derivation.makeConverter( + typeFields_js_1.InputTypes.TAP_BIP32_DERIVATION, + ), + tapInternalKey: tapInternalKey.makeConverter( + typeFields_js_1.InputTypes.TAP_INTERNAL_KEY, + ), + tapMerkleRoot, +}; +exports.inputs = inputs; +const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_js_1.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_js_1.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_js_1.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_js_1.OutputTypes.BIP32_DERIVATION, + ]), + tapBip32Derivation: tapBip32Derivation.makeConverter( + typeFields_js_1.OutputTypes.TAP_BIP32_DERIVATION, + ), + tapTree, + tapInternalKey: tapInternalKey.makeConverter( + typeFields_js_1.OutputTypes.TAP_INTERNAL_KEY, + ), +}; +exports.outputs = outputs; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptSig.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptSig.cjs new file mode 100644 index 0000000..2111e73 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptSig.cjs @@ -0,0 +1,42 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + const key = new Uint8Array([typeFields_js_1.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Uint8Array'; +function check(data) { + return data instanceof Uint8Array; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptWitness.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptWitness.cjs new file mode 100644 index 0000000..c76e2fb --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/finalScriptWitness.cjs @@ -0,0 +1,44 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + const key = new Uint8Array([typeFields_js_1.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Uint8Array'; +function check(data) { + return data instanceof Uint8Array; +} +exports.check = check; +function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/nonWitnessUtxo.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/nonWitnessUtxo.cjs new file mode 100644 index 0000000..f2451dc --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/nonWitnessUtxo.cjs @@ -0,0 +1,41 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + return { + key: new Uint8Array([typeFields_js_1.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Uint8Array'; +function check(data) { + return data instanceof Uint8Array; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/partialSig.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/partialSig.cjs new file mode 100644 index 0000000..6c50212 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/partialSig.cjs @@ -0,0 +1,79 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; +} +exports.decode = decode; +function encode(pSig) { + const head = new Uint8Array([typeFields_js_1.InputTypes.PARTIAL_SIG]); + return { + key: tools.concat([head, pSig.pubkey]), + value: pSig.signature, + }; +} +exports.encode = encode; +exports.expected = '{ pubkey: Uint8Array; signature: Uint8Array; }'; +function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.signature instanceof Uint8Array && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); +} +exports.check = check; +function isDerSigWithSighash(buf) { + if (!(buf instanceof Uint8Array) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; +} +function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.pubkey, item.pubkey) === 0).length === 0 + ); +} +exports.canAddToArray = canAddToArray; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/porCommitment.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/porCommitment.cjs new file mode 100644 index 0000000..47b8340 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/porCommitment.cjs @@ -0,0 +1,42 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + tools.toHex(keyVal.key), + ); + } + return tools.toUtf8(keyVal.value); +} +exports.decode = decode; +function encode(data) { + const key = new Uint8Array([typeFields_js_1.InputTypes.POR_COMMITMENT]); + return { + key, + value: tools.fromUtf8(data), + }; +} +exports.encode = encode; +exports.expected = 'string'; +function check(data) { + return typeof data === 'string'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/sighashType.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/sighashType.cjs new file mode 100644 index 0000000..263dd28 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/sighashType.cjs @@ -0,0 +1,44 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + tools.toHex(keyVal.key), + ); + } + return Number(tools.readUInt32(keyVal.value, 0, 'LE')); +} +exports.decode = decode; +function encode(data) { + const key = Uint8Array.from([typeFields_js_1.InputTypes.SIGHASH_TYPE]); + const value = new Uint8Array(4); + tools.writeUInt32(value, 0, data, 'LE'); + return { + key, + value, + }; +} +exports.encode = encode; +exports.expected = 'number'; +function check(data) { + return typeof data === 'number'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapKeySig.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapKeySig.cjs new file mode 100644 index 0000000..c28a6a3 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapKeySig.cjs @@ -0,0 +1,49 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_js_1.InputTypes.TAP_KEY_SIG || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapKeySig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (!check(keyVal.value)) { + throw new Error( + 'Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature', + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(value) { + const key = Uint8Array.from([typeFields_js_1.InputTypes.TAP_KEY_SIG]); + return { key, value }; +} +exports.encode = encode; +exports.expected = 'Uint8Array'; +function check(data) { + return ( + data instanceof Uint8Array && (data.length === 64 || data.length === 65) + ); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapKeySig === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapLeafScript.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapLeafScript.cjs new file mode 100644 index 0000000..d3feb6b --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapLeafScript.cjs @@ -0,0 +1,70 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.TAP_LEAF_SCRIPT) { + throw new Error( + 'Decode Error: could not decode tapLeafScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.key.length - 2) % 32 !== 0) { + throw new Error( + 'Decode Error: tapLeafScript has invalid control block in key 0x' + + tools.toHex(keyVal.key), + ); + } + const leafVersion = keyVal.value[keyVal.value.length - 1]; + if ((keyVal.key[1] & 0xfe) !== leafVersion) { + throw new Error( + 'Decode Error: tapLeafScript bad leaf version in key 0x' + + tools.toHex(keyVal.key), + ); + } + const script = keyVal.value.slice(0, -1); + const controlBlock = keyVal.key.slice(1); + return { controlBlock, script, leafVersion }; +} +exports.decode = decode; +function encode(tScript) { + const head = Uint8Array.from([typeFields_js_1.InputTypes.TAP_LEAF_SCRIPT]); + const verBuf = Uint8Array.from([tScript.leafVersion]); + return { + key: tools.concat([head, tScript.controlBlock]), + value: tools.concat([tScript.script, verBuf]), + }; +} +exports.encode = encode; +exports.expected = + '{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }'; +function check(data) { + return ( + data.controlBlock instanceof Uint8Array && + (data.controlBlock.length - 1) % 32 === 0 && + (data.controlBlock[0] & 0xfe) === data.leafVersion && + data.script instanceof Uint8Array + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.controlBlock); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.controlBlock, item.controlBlock) === 0) + .length === 0 + ); +} +exports.canAddToArray = canAddToArray; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapMerkleRoot.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapMerkleRoot.cjs new file mode 100644 index 0000000..df22167 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapMerkleRoot.cjs @@ -0,0 +1,45 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_js_1.InputTypes.TAP_MERKLE_ROOT || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapMerkleRoot with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (!check(keyVal.value)) { + throw new Error('Decode Error: tapMerkleRoot not a 32-byte hash'); + } + return keyVal.value; +} +exports.decode = decode; +function encode(value) { + const key = Uint8Array.from([typeFields_js_1.InputTypes.TAP_MERKLE_ROOT]); + return { key, value }; +} +exports.encode = encode; +exports.expected = 'Uint8Array'; +function check(data) { + return data instanceof Uint8Array && data.length === 32; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapMerkleRoot === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapScriptSig.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapScriptSig.cjs new file mode 100644 index 0000000..818fad1 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/tapScriptSig.cjs @@ -0,0 +1,76 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.TAP_SCRIPT_SIG) { + throw new Error( + 'Decode Error: could not decode tapScriptSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.key.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid key 0x' + tools.toHex(keyVal.key), + ); + } + if (keyVal.value.length !== 64 && keyVal.value.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid signature in key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1, 33); + const leafHash = keyVal.key.slice(33); + return { + pubkey, + leafHash, + signature: keyVal.value, + }; +} +exports.decode = decode; +function encode(tSig) { + const head = Uint8Array.from([typeFields_js_1.InputTypes.TAP_SCRIPT_SIG]); + return { + key: tools.concat([head, tSig.pubkey, tSig.leafHash]), + value: tSig.signature, + }; +} +exports.encode = encode; +exports.expected = + '{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }'; +function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.leafHash instanceof Uint8Array && + data.signature instanceof Uint8Array && + data.pubkey.length === 32 && + data.leafHash.length === 32 && + (data.signature.length === 64 || data.signature.length === 65) + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey) + tools.toHex(item.leafHash); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter( + v => + tools.compare(v.pubkey, item.pubkey) === 0 && + tools.compare(v.leafHash, item.leafHash) === 0, + ).length === 0 + ); +} +exports.canAddToArray = canAddToArray; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/witnessUtxo.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/witnessUtxo.cjs new file mode 100644 index 0000000..3979d9d --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/input/witnessUtxo.cjs @@ -0,0 +1,62 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const tools = __importStar(require('uint8array-tools')); +const varuint = __importStar(require('varuint-bitcoin')); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_js_1.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + tools.toHex(keyVal.key), + ); + } + const value = tools.readInt64(keyVal.value, 0, 'LE'); + let _offset = 8; + const { numberValue: scriptLen, bytes } = varuint.decode( + keyVal.value, + _offset, + ); + _offset += bytes; + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; +} +exports.decode = decode; +function encode(data) { + const { script, value } = data; + const varuintlen = varuint.encodingLength(script.length); + const result = new Uint8Array(8 + varuintlen + script.length); + tools.writeInt64(result, 0, BigInt(value), 'LE'); + varuint.encode(script.length, result, 8); + result.set(script, 8 + varuintlen); + return { + key: Uint8Array.from([typeFields_js_1.InputTypes.WITNESS_UTXO]), + value: result, + }; +} +exports.encode = encode; +exports.expected = '{ script: Uint8Array; value: bigint; }'; +function check(data) { + return data.script instanceof Uint8Array && typeof data.value === 'bigint'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/output/tapTree.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/output/tapTree.cjs new file mode 100644 index 0000000..8fd1dd4 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/output/tapTree.cjs @@ -0,0 +1,80 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_js_1 = require('../../typeFields.cjs'); +const varuint = __importStar(require('varuint-bitcoin')); +const tools = __importStar(require('uint8array-tools')); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_js_1.OutputTypes.TAP_TREE || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapTree with key 0x' + + tools.toHex(keyVal.key), + ); + } + let _offset = 0; + const data = []; + while (_offset < keyVal.value.length) { + const depth = keyVal.value[_offset++]; + const leafVersion = keyVal.value[_offset++]; + const { numberValue: scriptLen, bytes } = varuint.decode( + keyVal.value, + _offset, + ); + _offset += bytes; + data.push({ + depth, + leafVersion, + script: keyVal.value.slice(_offset, _offset + scriptLen), + }); + _offset += scriptLen; + } + return { leaves: data }; +} +exports.decode = decode; +function encode(tree) { + const key = Uint8Array.from([typeFields_js_1.OutputTypes.TAP_TREE]); + const bufs = [].concat( + ...tree.leaves.map(tapLeaf => [ + Uint8Array.of(tapLeaf.depth, tapLeaf.leafVersion), + varuint.encode(BigInt(tapLeaf.script.length)).buffer, + tapLeaf.script, + ]), + ); + return { + key, + value: tools.concat(bufs), + }; +} +exports.encode = encode; +exports.expected = + '{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }'; +function check(data) { + return ( + Array.isArray(data.leaves) && + data.leaves.every( + tapLeaf => + tapLeaf.depth >= 0 && + tapLeaf.depth <= 128 && + (tapLeaf.leafVersion & 0xfe) === tapLeaf.leafVersion && + tapLeaf.script instanceof Uint8Array, + ) + ); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapTree === undefined; +} +exports.canAdd = canAdd; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/bip32Derivation.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/bip32Derivation.cjs new file mode 100644 index 0000000..5a074b6 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/bip32Derivation.cjs @@ -0,0 +1,98 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const tools = __importStar(require('uint8array-tools')); +const range = n => [...Array(n).keys()]; +const isValidDERKey = pubkey => + (pubkey.length === 33 && [2, 3].includes(pubkey[0])) || + (pubkey.length === 65 && 4 === pubkey[0]); +function makeConverter(TYPE_BYTE, isValidPubkey = isValidDERKey) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1); + if (!isValidPubkey(pubkey)) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = tools.readUInt32(keyVal.value, i * 4 + 4, 'LE'); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Uint8Array.from([TYPE_BYTE]); + const key = tools.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = new Uint8Array(splitPath.length * 4); + value.set(data.masterFingerprint, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + tools.writeUInt32(value, offset, num, 'LE'); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; }'; + function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.masterFingerprint instanceof Uint8Array && + typeof data.path === 'string' && + isValidPubkey(data.pubkey) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.pubkey, item.pubkey) === 0).length === 0 + ); + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; +} +exports.makeConverter = makeConverter; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/checkPubkey.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/checkPubkey.cjs new file mode 100644 index 0000000..3498a6a --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/checkPubkey.cjs @@ -0,0 +1,33 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const tools = __importStar(require('uint8array-tools')); +function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + tools.toHex(keyVal.key), + ); + } + } + return pubkey; + } +} +exports.makeChecker = makeChecker; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/redeemScript.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/redeemScript.cjs new file mode 100644 index 0000000..9fbdfe9 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/redeemScript.cjs @@ -0,0 +1,47 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const tools = __importStar(require('uint8array-tools')); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Uint8Array.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array; + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapBip32Derivation.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapBip32Derivation.cjs new file mode 100644 index 0000000..5d89b4c --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapBip32Derivation.cjs @@ -0,0 +1,66 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const varuint = __importStar(require('varuint-bitcoin')); +const tools = __importStar(require('uint8array-tools')); +const bip32Derivation = __importStar(require('./bip32Derivation.cjs')); +const isValidBIP340Key = pubkey => pubkey.length === 32; +function makeConverter(TYPE_BYTE) { + const parent = bip32Derivation.makeConverter(TYPE_BYTE, isValidBIP340Key); + function decode(keyVal) { + const { numberValue: nHashes, bytes: nHashesLen } = varuint.decode( + keyVal.value, + ); + const base = parent.decode({ + key: keyVal.key, + value: keyVal.value.slice(nHashesLen + Number(nHashes) * 32), + }); + const leafHashes = new Array(Number(nHashes)); + for (let i = 0, _offset = nHashesLen; i < nHashes; i++, _offset += 32) { + leafHashes[i] = keyVal.value.slice(_offset, _offset + 32); + } + return { ...base, leafHashes }; + } + function encode(data) { + const base = parent.encode(data); + const nHashesLen = varuint.encodingLength(data.leafHashes.length); + const nHashesBuf = new Uint8Array(nHashesLen); + varuint.encode(data.leafHashes.length, nHashesBuf); + const value = tools.concat([nHashesBuf, ...data.leafHashes, base.value]); + return { ...base, value }; + } + const expected = + '{ ' + + 'masterFingerprint: Uint8Array; ' + + 'pubkey: Uint8Array; ' + + 'path: string; ' + + 'leafHashes: Uint8Array[]; ' + + '}'; + function check(data) { + return ( + Array.isArray(data.leafHashes) && + data.leafHashes.every( + leafHash => leafHash instanceof Uint8Array && leafHash.length === 32, + ) && + parent.check(data) + ); + } + return { + decode, + encode, + check, + expected, + canAddToArray: parent.canAddToArray, + }; +} +exports.makeConverter = makeConverter; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapInternalKey.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapInternalKey.cjs new file mode 100644 index 0000000..6f915aa --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/tapInternalKey.cjs @@ -0,0 +1,51 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const tools = __importStar(require('uint8array-tools')); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapInternalKey with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.value.length !== 32) { + throw new Error( + 'Decode Error: tapInternalKey not a 32-byte x-only pubkey', + ); + } + return keyVal.value; + } + function encode(value) { + const key = Uint8Array.from([TYPE_BYTE]); + return { key, value }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array && data.length === 32; + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.tapInternalKey === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/witnessScript.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/witnessScript.cjs new file mode 100644 index 0000000..c31be2c --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/shared/witnessScript.cjs @@ -0,0 +1,49 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const tools = __importStar(require('uint8array-tools')); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Uint8Array.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array; + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/converter/tools.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/tools.cjs new file mode 100644 index 0000000..7379f34 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/converter/tools.cjs @@ -0,0 +1,48 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const varuint = __importStar(require('varuint-bitcoin')); +const tools = __importStar(require('uint8array-tools')); +exports.range = n => [...Array(n).keys()]; +function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +exports.reverseBuffer = reverseBuffer; +function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Uint8Array.from([0])); + return tools.concat(buffers); +} +exports.keyValsToBuffer = keyValsToBuffer; +function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint.encodingLength(keyLen); + const valVarIntLen = varuint.encodingLength(valLen); + const buffer = new Uint8Array(keyVarIntLen + keyLen + valVarIntLen + valLen); + varuint.encode(keyLen, buffer, 0); + buffer.set(keyVal.key, keyVarIntLen); + varuint.encode(valLen, buffer, keyVarIntLen + keyLen); + buffer.set(keyVal.value, keyVarIntLen + keyLen + valVarIntLen); + return buffer; +} +exports.keyValToBuffer = keyValToBuffer; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/interfaces.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/interfaces.cjs new file mode 100644 index 0000000..db8b17d --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/interfaces.cjs @@ -0,0 +1,2 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/parser/fromBuffer.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/fromBuffer.cjs new file mode 100644 index 0000000..2492341 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/fromBuffer.cjs @@ -0,0 +1,409 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const convert = __importStar(require('../converter/index.cjs')); +const tools_js_1 = require('../converter/tools.cjs'); +const varuint = __importStar(require('varuint-bitcoin')); +const tools = __importStar(require('uint8array-tools')); +const typeFields_js_1 = require('../typeFields.cjs'); +function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const { numberValue: keyLen, bytes } = varuint.decode(buffer, offset); + offset += bytes; + const key = buffer.slice(offset, offset + Number(keyLen)); + offset += Number(keyLen); + return key; + } + function readUInt32BE() { + const num = tools.readUInt32(buffer, offset, 'BE'); + offset += 4; + return num; + } + function readUInt8() { + const num = tools.readUInt8(buffer, offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = tools.readUInt8(buffer, offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_js_1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_js_1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_js_1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); +} +exports.psbtFromBuffer = psbtFromBuffer; +function checkKeyBuffer(type, keyBuf, keyNum) { + if (tools.compare(keyBuf, Uint8Array.from([keyNum]))) { + throw new Error( + // `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + `Format Error: Invalid ${type} key: ${tools.toHex(keyBuf)}`, + ); + } +} +exports.checkKeyBuffer = checkKeyBuffer; +function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, +) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_js_1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_js_1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_js_1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_js_1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_js_1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_js_1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_js_1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert.inputs.partialSig.decode(keyVal)); + break; + case typeFields_js_1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert.inputs.sighashType.decode(keyVal); + break; + case typeFields_js_1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert.inputs.redeemScript.decode(keyVal); + break; + case typeFields_js_1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert.inputs.witnessScript.decode(keyVal); + break; + case typeFields_js_1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_js_1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_js_1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_js_1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert.inputs.porCommitment.decode(keyVal); + break; + case typeFields_js_1.InputTypes.TAP_KEY_SIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.TAP_KEY_SIG, + ); + input.tapKeySig = convert.inputs.tapKeySig.decode(keyVal); + break; + case typeFields_js_1.InputTypes.TAP_SCRIPT_SIG: + if (input.tapScriptSig === undefined) { + input.tapScriptSig = []; + } + input.tapScriptSig.push(convert.inputs.tapScriptSig.decode(keyVal)); + break; + case typeFields_js_1.InputTypes.TAP_LEAF_SCRIPT: + if (input.tapLeafScript === undefined) { + input.tapLeafScript = []; + } + input.tapLeafScript.push(convert.inputs.tapLeafScript.decode(keyVal)); + break; + case typeFields_js_1.InputTypes.TAP_BIP32_DERIVATION: + if (input.tapBip32Derivation === undefined) { + input.tapBip32Derivation = []; + } + input.tapBip32Derivation.push( + convert.inputs.tapBip32Derivation.decode(keyVal), + ); + break; + case typeFields_js_1.InputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.TAP_INTERNAL_KEY, + ); + input.tapInternalKey = convert.inputs.tapInternalKey.decode(keyVal); + break; + case typeFields_js_1.InputTypes.TAP_MERKLE_ROOT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_js_1.InputTypes.TAP_MERKLE_ROOT, + ); + input.tapMerkleRoot = convert.inputs.tapMerkleRoot.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_js_1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_js_1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_js_1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert.outputs.redeemScript.decode(keyVal); + break; + case typeFields_js_1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_js_1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert.outputs.witnessScript.decode(keyVal); + break; + case typeFields_js_1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert.outputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_js_1.OutputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_js_1.OutputTypes.TAP_INTERNAL_KEY, + ); + output.tapInternalKey = convert.outputs.tapInternalKey.decode(keyVal); + break; + case typeFields_js_1.OutputTypes.TAP_TREE: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_js_1.OutputTypes.TAP_TREE, + ); + output.tapTree = convert.outputs.tapTree.decode(keyVal); + break; + case typeFields_js_1.OutputTypes.TAP_BIP32_DERIVATION: + if (output.tapBip32Derivation === undefined) { + output.tapBip32Derivation = []; + } + output.tapBip32Derivation.push( + convert.outputs.tapBip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; +} +exports.psbtFromKeyVals = psbtFromKeyVals; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/parser/index.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/index.cjs new file mode 100644 index 0000000..ceb0073 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/index.cjs @@ -0,0 +1,7 @@ +'use strict'; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, '__esModule', { value: true }); +__export(require('./fromBuffer.cjs')); +__export(require('./toBuffer.cjs')); diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/parser/toBuffer.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/toBuffer.cjs new file mode 100644 index 0000000..c9e9192 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/parser/toBuffer.cjs @@ -0,0 +1,76 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const convert = __importStar(require('../converter/index.cjs')); +const tools_js_1 = require('../converter/tools.cjs'); +const tools = __importStar(require('uint8array-tools')); +function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_js_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Uint8Array.from([0])] + : keyVals.map(tools_js_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = new Uint8Array(5); + header.set([0x70, 0x73, 0x62, 0x74, 0xff], 0); + return tools.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); +} +exports.psbtToBuffer = psbtToBuffer; +const sortKeyVals = (a, b) => { + return tools.compare(a.key, b.key); +}; +function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => tools.toHex(kv.key)); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(tools.toHex(keyVal.key)); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); +} +function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; +} +exports.psbtToKeyVals = psbtToKeyVals; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/psbt.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/psbt.cjs new file mode 100644 index 0000000..2118dda --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/psbt.cjs @@ -0,0 +1,163 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const index_js_1 = require('./combiner/index.cjs'); +const index_js_2 = require('./parser/index.cjs'); +const typeFields_js_1 = require('./typeFields.cjs'); +const utils_js_1 = require('./utils.cjs'); +const tools = __importStar(require('uint8array-tools')); +class Psbt { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = tools.fromBase64(data); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = tools.fromHex(data); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = index_js_2.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return tools.toBase64(buffer); + } + toHex() { + const buffer = this.toBuffer(); + return tools.toHex(buffer); + } + toBuffer() { + return index_js_2.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_js_1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_js_1.checkForInput(this.inputs, inputIndex); + utils_js_1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_js_1.checkForOutput(this.outputs, outputIndex); + utils_js_1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_js_1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_js_1.getEnumLength(typeFields_js_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_js_1.checkForInput(this.inputs, inputIndex); + utils_js_1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_js_1.getEnumLength(typeFields_js_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_js_1.checkForOutput(this.outputs, outputIndex); + utils_js_1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_js_1.getEnumLength(typeFields_js_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_js_1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToOutput(outputIndex, keyVal), + ); + utils_js_1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_js_1.checkForInput(this.inputs, inputIndex); + utils_js_1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = index_js_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } +} +exports.Psbt = Psbt; +var utils_js_2 = require('./utils.cjs'); +exports.checkForInput = utils_js_2.checkForInput; +exports.checkForOutput = utils_js_2.checkForOutput; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/typeFields.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/typeFields.cjs new file mode 100644 index 0000000..f4b1d12 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/typeFields.cjs @@ -0,0 +1,64 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +var GlobalTypes; +(function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; +})((GlobalTypes = exports.GlobalTypes || (exports.GlobalTypes = {}))); +exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; +var InputTypes; +(function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + InputTypes[(InputTypes['TAP_KEY_SIG'] = 19)] = 'TAP_KEY_SIG'; + InputTypes[(InputTypes['TAP_SCRIPT_SIG'] = 20)] = 'TAP_SCRIPT_SIG'; + InputTypes[(InputTypes['TAP_LEAF_SCRIPT'] = 21)] = 'TAP_LEAF_SCRIPT'; + InputTypes[(InputTypes['TAP_BIP32_DERIVATION'] = 22)] = + 'TAP_BIP32_DERIVATION'; + InputTypes[(InputTypes['TAP_INTERNAL_KEY'] = 23)] = 'TAP_INTERNAL_KEY'; + InputTypes[(InputTypes['TAP_MERKLE_ROOT'] = 24)] = 'TAP_MERKLE_ROOT'; +})((InputTypes = exports.InputTypes || (exports.InputTypes = {}))); +exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + 'tapKeySig', + 'tapScriptSig', + 'tapLeafScript', + 'tapBip32Derivation', + 'tapInternalKey', + 'tapMerkleRoot', +]; +var OutputTypes; +(function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + OutputTypes[(OutputTypes['TAP_INTERNAL_KEY'] = 5)] = 'TAP_INTERNAL_KEY'; + OutputTypes[(OutputTypes['TAP_TREE'] = 6)] = 'TAP_TREE'; + OutputTypes[(OutputTypes['TAP_BIP32_DERIVATION'] = 7)] = + 'TAP_BIP32_DERIVATION'; +})((OutputTypes = exports.OutputTypes || (exports.OutputTypes = {}))); +exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'tapInternalKey', + 'tapTree', + 'tapBip32Derivation', +]; diff --git a/src/libMPC/node_modules/bip174/src/cjs/lib/utils.cjs b/src/libMPC/node_modules/bip174/src/cjs/lib/utils.cjs new file mode 100644 index 0000000..57bcabb --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/cjs/lib/utils.cjs @@ -0,0 +1,152 @@ +'use strict'; +var __importStar = + (this && this.__importStar) || + function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result['default'] = mod; + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const converter = __importStar(require('./converter/index.cjs')); +const tools = __importStar(require('uint8array-tools')); +function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; +} +exports.checkForInput = checkForInput; +function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; +} +exports.checkForOutput = checkForOutput; +function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => tools.compare(kv.key, checkKeyVal.key) === 0) + .length !== 0 + ) { + throw new Error(`Duplicate Key: ${tools.toHex(checkKeyVal.key)}`); + } +} +exports.checkHasKey = checkHasKey; +function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; +} +exports.getEnumLength = getEnumLength; +function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } +} +exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; +function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); +} +function updateMaker(typeName) { + return (updateData, mainData) => { + // @ts-ignore + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; +} +exports.updateGlobal = updateMaker('global'); +exports.updateInput = updateMaker('input'); +exports.updateOutput = updateMaker('output'); +function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); +} +exports.addInputAttributes = addInputAttributes; +function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForOutput(outputs, index); + exports.updateOutput(data, output); +} +exports.addOutputAttributes = addOutputAttributes; +function defaultVersionSetter(version, txBuf) { + if (!(txBuf instanceof Uint8Array) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + tools.writeUInt32(txBuf, 0, version, 'LE'); + return txBuf; +} +exports.defaultVersionSetter = defaultVersionSetter; +function defaultLocktimeSetter(locktime, txBuf) { + if (!(txBuf instanceof Uint8Array) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + tools.writeUInt32(txBuf, txBuf.length - 4, locktime, 'LE'); + return txBuf; +} +exports.defaultLocktimeSetter = defaultLocktimeSetter; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.d.ts new file mode 100644 index 0000000..f4ebd8c --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.d.ts @@ -0,0 +1,2 @@ +import { PsbtAttributes } from '../parser/index.js'; +export declare function combine(psbts: PsbtAttributes[]): PsbtAttributes; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.js b/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.js new file mode 100644 index 0000000..bb4e01b --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/combiner/index.js @@ -0,0 +1,81 @@ +import { psbtFromKeyVals, psbtToKeyVals } from '../parser/index.js'; +import * as tools from 'uint8array-tools'; +export function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + tools.compare(otherTx.toBuffer(), selfTx.toBuffer()) !== 0 + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); +} +function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => tools.toHex(kv.key) === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; +} +function getTx(psbt) { + return psbt.globalMap.unsignedTx; +} +function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = tools.toHex(keyVal.key); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.d.ts new file mode 100644 index 0000000..a3b0d11 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.d.ts @@ -0,0 +1,6 @@ +import { GlobalXpub, KeyValue } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): GlobalXpub; +export declare function encode(data: GlobalXpub): KeyValue; +export declare const expected = "{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }"; +export declare function check(data: any): data is GlobalXpub; +export declare function canAddToArray(array: GlobalXpub[], item: GlobalXpub, dupeSet: Set): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.js new file mode 100644 index 0000000..b9596f7 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/globalXpub.js @@ -0,0 +1,79 @@ +import { GlobalTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +const range = n => [...Array(n).keys()]; +export function decode(keyVal) { + if (keyVal.key[0] !== GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = tools.readUInt32(keyVal.value, i * 4 + 4, 'LE'); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; +} +export function encode(data) { + const head = new Uint8Array([GlobalTypes.GLOBAL_XPUB]); + const key = tools.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = new Uint8Array(splitPath.length * 4); + value.set(data.masterFingerprint, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + tools.writeUInt32(value, offset, num, 'LE'); + offset += 4; + }); + return { + key, + value, + }; +} +export const expected = + '{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }'; +export function check(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + epk instanceof Uint8Array && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + mfp instanceof Uint8Array && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)*$/) + ); +} +export function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.extendedPubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.extendedPubkey, item.extendedPubkey)) + .length === 0 + ); +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.d.ts new file mode 100644 index 0000000..ddcdce4 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.d.ts @@ -0,0 +1,2 @@ +import { KeyValue, Transaction } from '../../interfaces'; +export declare function encode(data: Transaction): KeyValue; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.js new file mode 100644 index 0000000..fc5038a --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/global/unsignedTx.js @@ -0,0 +1,7 @@ +import { GlobalTypes } from '../../typeFields.js'; +export function encode(data) { + return { + key: new Uint8Array([GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.d.ts new file mode 100644 index 0000000..f152688 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.d.ts @@ -0,0 +1,108 @@ +import * as globalXpub from './global/globalXpub.js'; +import * as unsignedTx from './global/unsignedTx.js'; +import * as finalScriptSig from './input/finalScriptSig.js'; +import * as finalScriptWitness from './input/finalScriptWitness.js'; +import * as nonWitnessUtxo from './input/nonWitnessUtxo.js'; +import * as partialSig from './input/partialSig.js'; +import * as porCommitment from './input/porCommitment.js'; +import * as sighashType from './input/sighashType.js'; +import * as tapKeySig from './input/tapKeySig.js'; +import * as tapLeafScript from './input/tapLeafScript.js'; +import * as tapMerkleRoot from './input/tapMerkleRoot.js'; +import * as tapScriptSig from './input/tapScriptSig.js'; +import * as witnessUtxo from './input/witnessUtxo.js'; +import * as tapTree from './output/tapTree.js'; +declare const globals: { + unsignedTx: typeof unsignedTx; + globalXpub: typeof globalXpub; + checkPubkey: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array | undefined; +}; +declare const inputs: { + nonWitnessUtxo: typeof nonWitnessUtxo; + partialSig: typeof partialSig; + sighashType: typeof sighashType; + finalScriptSig: typeof finalScriptSig; + finalScriptWitness: typeof finalScriptWitness; + porCommitment: typeof porCommitment; + witnessUtxo: typeof witnessUtxo; + bip32Derivation: { + decode: (keyVal: import("../interfaces.js").KeyValue) => import("../interfaces.js").Bip32Derivation; + encode: (data: import("../interfaces.js").Bip32Derivation) => import("../interfaces.js").KeyValue; + check: (data: any) => data is import("../interfaces.js").Bip32Derivation; + expected: string; + canAddToArray: (array: import("../interfaces.js").Bip32Derivation[], item: import("../interfaces.js").Bip32Derivation, dupeSet: Set) => boolean; + }; + redeemScript: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; + witnessScript: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; + checkPubkey: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array | undefined; + tapKeySig: typeof tapKeySig; + tapScriptSig: typeof tapScriptSig; + tapLeafScript: typeof tapLeafScript; + tapBip32Derivation: { + decode: (keyVal: import("../interfaces.js").KeyValue) => import("../interfaces.js").TapBip32Derivation; + encode: (data: import("../interfaces.js").TapBip32Derivation) => import("../interfaces.js").KeyValue; + check: (data: any) => data is import("../interfaces.js").TapBip32Derivation; + expected: string; + canAddToArray: (array: import("../interfaces.js").TapBip32Derivation[], item: import("../interfaces.js").TapBip32Derivation, dupeSet: Set) => boolean; + }; + tapInternalKey: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; + tapMerkleRoot: typeof tapMerkleRoot; +}; +declare const outputs: { + bip32Derivation: { + decode: (keyVal: import("../interfaces.js").KeyValue) => import("../interfaces.js").Bip32Derivation; + encode: (data: import("../interfaces.js").Bip32Derivation) => import("../interfaces.js").KeyValue; + check: (data: any) => data is import("../interfaces.js").Bip32Derivation; + expected: string; + canAddToArray: (array: import("../interfaces.js").Bip32Derivation[], item: import("../interfaces.js").Bip32Derivation, dupeSet: Set) => boolean; + }; + redeemScript: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; + witnessScript: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; + checkPubkey: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array | undefined; + tapBip32Derivation: { + decode: (keyVal: import("../interfaces.js").KeyValue) => import("../interfaces.js").TapBip32Derivation; + encode: (data: import("../interfaces.js").TapBip32Derivation) => import("../interfaces.js").KeyValue; + check: (data: any) => data is import("../interfaces.js").TapBip32Derivation; + expected: string; + canAddToArray: (array: import("../interfaces.js").TapBip32Derivation[], item: import("../interfaces.js").TapBip32Derivation, dupeSet: Set) => boolean; + }; + tapTree: typeof tapTree; + tapInternalKey: { + decode: (keyVal: import("../interfaces.js").KeyValue) => Uint8Array; + encode: (data: Uint8Array) => import("../interfaces.js").KeyValue; + check: (data: any) => data is Uint8Array; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; + }; +}; +export { globals, inputs, outputs }; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.js new file mode 100644 index 0000000..a6e0dd5 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/index.js @@ -0,0 +1,63 @@ +import { InputTypes, OutputTypes } from '../typeFields.js'; +import * as globalXpub from './global/globalXpub.js'; +import * as unsignedTx from './global/unsignedTx.js'; +import * as finalScriptSig from './input/finalScriptSig.js'; +import * as finalScriptWitness from './input/finalScriptWitness.js'; +import * as nonWitnessUtxo from './input/nonWitnessUtxo.js'; +import * as partialSig from './input/partialSig.js'; +import * as porCommitment from './input/porCommitment.js'; +import * as sighashType from './input/sighashType.js'; +import * as tapKeySig from './input/tapKeySig.js'; +import * as tapLeafScript from './input/tapLeafScript.js'; +import * as tapMerkleRoot from './input/tapMerkleRoot.js'; +import * as tapScriptSig from './input/tapScriptSig.js'; +import * as witnessUtxo from './input/witnessUtxo.js'; +import * as tapTree from './output/tapTree.js'; +import * as bip32Derivation from './shared/bip32Derivation.js'; +import * as checkPubkey from './shared/checkPubkey.js'; +import * as redeemScript from './shared/redeemScript.js'; +import * as tapBip32Derivation from './shared/tapBip32Derivation.js'; +import * as tapInternalKey from './shared/tapInternalKey.js'; +import * as witnessScript from './shared/witnessScript.js'; +const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), +}; +const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter(InputTypes.BIP32_DERIVATION), + redeemScript: redeemScript.makeConverter(InputTypes.REDEEM_SCRIPT), + witnessScript: witnessScript.makeConverter(InputTypes.WITNESS_SCRIPT), + checkPubkey: checkPubkey.makeChecker([ + InputTypes.PARTIAL_SIG, + InputTypes.BIP32_DERIVATION, + ]), + tapKeySig, + tapScriptSig, + tapLeafScript, + tapBip32Derivation: tapBip32Derivation.makeConverter( + InputTypes.TAP_BIP32_DERIVATION, + ), + tapInternalKey: tapInternalKey.makeConverter(InputTypes.TAP_INTERNAL_KEY), + tapMerkleRoot, +}; +const outputs = { + bip32Derivation: bip32Derivation.makeConverter(OutputTypes.BIP32_DERIVATION), + redeemScript: redeemScript.makeConverter(OutputTypes.REDEEM_SCRIPT), + witnessScript: witnessScript.makeConverter(OutputTypes.WITNESS_SCRIPT), + checkPubkey: checkPubkey.makeChecker([OutputTypes.BIP32_DERIVATION]), + tapBip32Derivation: tapBip32Derivation.makeConverter( + OutputTypes.TAP_BIP32_DERIVATION, + ), + tapTree, + tapInternalKey: tapInternalKey.makeConverter(OutputTypes.TAP_INTERNAL_KEY), +}; +export { globals, inputs, outputs }; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.d.ts new file mode 100644 index 0000000..f08bc72 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.d.ts @@ -0,0 +1,6 @@ +import { FinalScriptSig, KeyValue } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): FinalScriptSig; +export declare function encode(data: FinalScriptSig): KeyValue; +export declare const expected = "Uint8Array"; +export declare function check(data: any): data is FinalScriptSig; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.js new file mode 100644 index 0000000..1a95767 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptSig.js @@ -0,0 +1,25 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +export function encode(data) { + const key = new Uint8Array([InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; +} +export const expected = 'Uint8Array'; +export function check(data) { + return data instanceof Uint8Array; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.d.ts new file mode 100644 index 0000000..aa64099 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.d.ts @@ -0,0 +1,6 @@ +import { FinalScriptWitness, KeyValue } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): FinalScriptWitness; +export declare function encode(data: FinalScriptWitness): KeyValue; +export declare const expected = "Uint8Array"; +export declare function check(data: any): data is FinalScriptWitness; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.js new file mode 100644 index 0000000..83851c1 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/finalScriptWitness.js @@ -0,0 +1,27 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +export function encode(data) { + const key = new Uint8Array([InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; +} +export const expected = 'Uint8Array'; +export function check(data) { + return data instanceof Uint8Array; +} +export function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.d.ts new file mode 100644 index 0000000..498a9ba --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, NonWitnessUtxo } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): NonWitnessUtxo; +export declare function encode(data: NonWitnessUtxo): KeyValue; +export declare const expected = "Uint8Array"; +export declare function check(data: any): data is NonWitnessUtxo; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.js new file mode 100644 index 0000000..0a296a4 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/nonWitnessUtxo.js @@ -0,0 +1,24 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; +} +export function encode(data) { + return { + key: new Uint8Array([InputTypes.NON_WITNESS_UTXO]), + value: data, + }; +} +export const expected = 'Uint8Array'; +export function check(data) { + return data instanceof Uint8Array; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.d.ts new file mode 100644 index 0000000..b7fd8c5 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, PartialSig } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): PartialSig; +export declare function encode(pSig: PartialSig): KeyValue; +export declare const expected = "{ pubkey: Uint8Array; signature: Uint8Array; }"; +export declare function check(data: any): data is PartialSig; +export declare function canAddToArray(array: PartialSig[], item: PartialSig, dupeSet: Set): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.js new file mode 100644 index 0000000..29b5d19 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/partialSig.js @@ -0,0 +1,62 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; +} +export function encode(pSig) { + const head = new Uint8Array([InputTypes.PARTIAL_SIG]); + return { + key: tools.concat([head, pSig.pubkey]), + value: pSig.signature, + }; +} +export const expected = '{ pubkey: Uint8Array; signature: Uint8Array; }'; +export function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.signature instanceof Uint8Array && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); +} +function isDerSigWithSighash(buf) { + if (!(buf instanceof Uint8Array) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; +} +export function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.pubkey, item.pubkey) === 0).length === 0 + ); +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.d.ts new file mode 100644 index 0000000..1f45bb3 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, PorCommitment } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): PorCommitment; +export declare function encode(data: PorCommitment): KeyValue; +export declare const expected = "string"; +export declare function check(data: any): data is PorCommitment; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.js new file mode 100644 index 0000000..71935ca --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/porCommitment.js @@ -0,0 +1,25 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + tools.toHex(keyVal.key), + ); + } + return tools.toUtf8(keyVal.value); +} +export function encode(data) { + const key = new Uint8Array([InputTypes.POR_COMMITMENT]); + return { + key, + value: tools.fromUtf8(data), + }; +} +export const expected = 'string'; +export function check(data) { + return typeof data === 'string'; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.d.ts new file mode 100644 index 0000000..a86e990 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, SighashType } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): SighashType; +export declare function encode(data: SighashType): KeyValue; +export declare const expected = "number"; +export declare function check(data: any): data is SighashType; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.js new file mode 100644 index 0000000..f67434e --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/sighashType.js @@ -0,0 +1,27 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + tools.toHex(keyVal.key), + ); + } + return Number(tools.readUInt32(keyVal.value, 0, 'LE')); +} +export function encode(data) { + const key = Uint8Array.from([InputTypes.SIGHASH_TYPE]); + const value = new Uint8Array(4); + tools.writeUInt32(value, 0, data, 'LE'); + return { + key, + value, + }; +} +export const expected = 'number'; +export function check(data) { + return typeof data === 'number'; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.d.ts new file mode 100644 index 0000000..07b357b --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, TapKeySig } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): TapKeySig; +export declare function encode(value: TapKeySig): KeyValue; +export declare const expected = "Uint8Array"; +export declare function check(data: any): data is TapKeySig; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.js new file mode 100644 index 0000000..5b6686d --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapKeySig.js @@ -0,0 +1,29 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.TAP_KEY_SIG || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapKeySig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (!check(keyVal.value)) { + throw new Error( + 'Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature', + ); + } + return keyVal.value; +} +export function encode(value) { + const key = Uint8Array.from([InputTypes.TAP_KEY_SIG]); + return { key, value }; +} +export const expected = 'Uint8Array'; +export function check(data) { + return ( + data instanceof Uint8Array && (data.length === 64 || data.length === 65) + ); +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapKeySig === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.d.ts new file mode 100644 index 0000000..f0ac9da --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, TapLeafScript } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): TapLeafScript; +export declare function encode(tScript: TapLeafScript): KeyValue; +export declare const expected = "{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }"; +export declare function check(data: any): data is TapLeafScript; +export declare function canAddToArray(array: TapLeafScript[], item: TapLeafScript, dupeSet: Set): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.js new file mode 100644 index 0000000..79bb32e --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapLeafScript.js @@ -0,0 +1,53 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.TAP_LEAF_SCRIPT) { + throw new Error( + 'Decode Error: could not decode tapLeafScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.key.length - 2) % 32 !== 0) { + throw new Error( + 'Decode Error: tapLeafScript has invalid control block in key 0x' + + tools.toHex(keyVal.key), + ); + } + const leafVersion = keyVal.value[keyVal.value.length - 1]; + if ((keyVal.key[1] & 0xfe) !== leafVersion) { + throw new Error( + 'Decode Error: tapLeafScript bad leaf version in key 0x' + + tools.toHex(keyVal.key), + ); + } + const script = keyVal.value.slice(0, -1); + const controlBlock = keyVal.key.slice(1); + return { controlBlock, script, leafVersion }; +} +export function encode(tScript) { + const head = Uint8Array.from([InputTypes.TAP_LEAF_SCRIPT]); + const verBuf = Uint8Array.from([tScript.leafVersion]); + return { + key: tools.concat([head, tScript.controlBlock]), + value: tools.concat([tScript.script, verBuf]), + }; +} +export const expected = + '{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }'; +export function check(data) { + return ( + data.controlBlock instanceof Uint8Array && + (data.controlBlock.length - 1) % 32 === 0 && + (data.controlBlock[0] & 0xfe) === data.leafVersion && + data.script instanceof Uint8Array + ); +} +export function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.controlBlock); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.controlBlock, item.controlBlock) === 0) + .length === 0 + ); +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.d.ts new file mode 100644 index 0000000..1e222dc --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, TapMerkleRoot } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): TapMerkleRoot; +export declare function encode(value: TapMerkleRoot): KeyValue; +export declare const expected = "Uint8Array"; +export declare function check(data: any): data is TapMerkleRoot; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.js new file mode 100644 index 0000000..d69a655 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapMerkleRoot.js @@ -0,0 +1,25 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.TAP_MERKLE_ROOT || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapMerkleRoot with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (!check(keyVal.value)) { + throw new Error('Decode Error: tapMerkleRoot not a 32-byte hash'); + } + return keyVal.value; +} +export function encode(value) { + const key = Uint8Array.from([InputTypes.TAP_MERKLE_ROOT]); + return { key, value }; +} +export const expected = 'Uint8Array'; +export function check(data) { + return data instanceof Uint8Array && data.length === 32; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapMerkleRoot === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.d.ts new file mode 100644 index 0000000..6172daa --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, TapScriptSig } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): TapScriptSig; +export declare function encode(tSig: TapScriptSig): KeyValue; +export declare const expected = "{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }"; +export declare function check(data: any): data is TapScriptSig; +export declare function canAddToArray(array: TapScriptSig[], item: TapScriptSig, dupeSet: Set): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.js new file mode 100644 index 0000000..03f1307 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/tapScriptSig.js @@ -0,0 +1,59 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.TAP_SCRIPT_SIG) { + throw new Error( + 'Decode Error: could not decode tapScriptSig with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.key.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid key 0x' + tools.toHex(keyVal.key), + ); + } + if (keyVal.value.length !== 64 && keyVal.value.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid signature in key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1, 33); + const leafHash = keyVal.key.slice(33); + return { + pubkey, + leafHash, + signature: keyVal.value, + }; +} +export function encode(tSig) { + const head = Uint8Array.from([InputTypes.TAP_SCRIPT_SIG]); + return { + key: tools.concat([head, tSig.pubkey, tSig.leafHash]), + value: tSig.signature, + }; +} +export const expected = + '{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }'; +export function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.leafHash instanceof Uint8Array && + data.signature instanceof Uint8Array && + data.pubkey.length === 32 && + data.leafHash.length === 32 && + (data.signature.length === 64 || data.signature.length === 65) + ); +} +export function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey) + tools.toHex(item.leafHash); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter( + v => + tools.compare(v.pubkey, item.pubkey) === 0 && + tools.compare(v.leafHash, item.leafHash) === 0, + ).length === 0 + ); +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.d.ts new file mode 100644 index 0000000..f670563 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, WitnessUtxo } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): WitnessUtxo; +export declare function encode(data: WitnessUtxo): KeyValue; +export declare const expected = "{ script: Uint8Array; value: bigint; }"; +export declare function check(data: any): data is WitnessUtxo; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.js new file mode 100644 index 0000000..75f6177 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/input/witnessUtxo.js @@ -0,0 +1,45 @@ +import { InputTypes } from '../../typeFields.js'; +import * as tools from 'uint8array-tools'; +import * as varuint from 'varuint-bitcoin'; +export function decode(keyVal) { + if (keyVal.key[0] !== InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + tools.toHex(keyVal.key), + ); + } + const value = tools.readInt64(keyVal.value, 0, 'LE'); + let _offset = 8; + const { numberValue: scriptLen, bytes } = varuint.decode( + keyVal.value, + _offset, + ); + _offset += bytes; + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; +} +export function encode(data) { + const { script, value } = data; + const varuintlen = varuint.encodingLength(script.length); + const result = new Uint8Array(8 + varuintlen + script.length); + tools.writeInt64(result, 0, BigInt(value), 'LE'); + varuint.encode(script.length, result, 8); + result.set(script, 8 + varuintlen); + return { + key: Uint8Array.from([InputTypes.WITNESS_UTXO]), + value: result, + }; +} +export const expected = '{ script: Uint8Array; value: bigint; }'; +export function check(data) { + return data.script instanceof Uint8Array && typeof data.value === 'bigint'; +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.d.ts new file mode 100644 index 0000000..f976363 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.d.ts @@ -0,0 +1,6 @@ +import { KeyValue, TapTree } from '../../interfaces'; +export declare function decode(keyVal: KeyValue): TapTree; +export declare function encode(tree: TapTree): KeyValue; +export declare const expected = "{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }"; +export declare function check(data: any): data is TapTree; +export declare function canAdd(currentData: any, newData: any): boolean; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.js new file mode 100644 index 0000000..afb4bfb --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/output/tapTree.js @@ -0,0 +1,60 @@ +import { OutputTypes } from '../../typeFields.js'; +import * as varuint from 'varuint-bitcoin'; +import * as tools from 'uint8array-tools'; +export function decode(keyVal) { + if (keyVal.key[0] !== OutputTypes.TAP_TREE || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapTree with key 0x' + + tools.toHex(keyVal.key), + ); + } + let _offset = 0; + const data = []; + while (_offset < keyVal.value.length) { + const depth = keyVal.value[_offset++]; + const leafVersion = keyVal.value[_offset++]; + const { numberValue: scriptLen, bytes } = varuint.decode( + keyVal.value, + _offset, + ); + _offset += bytes; + data.push({ + depth, + leafVersion, + script: keyVal.value.slice(_offset, _offset + scriptLen), + }); + _offset += scriptLen; + } + return { leaves: data }; +} +export function encode(tree) { + const key = Uint8Array.from([OutputTypes.TAP_TREE]); + const bufs = [].concat( + ...tree.leaves.map(tapLeaf => [ + Uint8Array.of(tapLeaf.depth, tapLeaf.leafVersion), + varuint.encode(BigInt(tapLeaf.script.length)).buffer, + tapLeaf.script, + ]), + ); + return { + key, + value: tools.concat(bufs), + }; +} +export const expected = + '{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }'; +export function check(data) { + return ( + Array.isArray(data.leaves) && + data.leaves.every( + tapLeaf => + tapLeaf.depth >= 0 && + tapLeaf.depth <= 128 && + (tapLeaf.leafVersion & 0xfe) === tapLeaf.leafVersion && + tapLeaf.script instanceof Uint8Array, + ) + ); +} +export function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapTree === undefined; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.d.ts new file mode 100644 index 0000000..d3b646d --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.d.ts @@ -0,0 +1,8 @@ +import { Bip32Derivation, KeyValue } from '../../interfaces'; +export declare function makeConverter(TYPE_BYTE: number, isValidPubkey?: (pubkey: Uint8Array) => boolean): { + decode: (keyVal: KeyValue) => Bip32Derivation; + encode: (data: Bip32Derivation) => KeyValue; + check: (data: any) => data is Bip32Derivation; + expected: string; + canAddToArray: (array: Bip32Derivation[], item: Bip32Derivation, dupeSet: Set) => boolean; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.js new file mode 100644 index 0000000..0bf45db --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/bip32Derivation.js @@ -0,0 +1,84 @@ +import * as tools from 'uint8array-tools'; +const range = n => [...Array(n).keys()]; +const isValidDERKey = pubkey => + (pubkey.length === 33 && [2, 3].includes(pubkey[0])) || + (pubkey.length === 65 && 4 === pubkey[0]); +export function makeConverter(TYPE_BYTE, isValidPubkey = isValidDERKey) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + tools.toHex(keyVal.key), + ); + } + const pubkey = keyVal.key.slice(1); + if (!isValidPubkey(pubkey)) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + tools.toHex(keyVal.key), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = tools.readUInt32(keyVal.value, i * 4 + 4, 'LE'); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Uint8Array.from([TYPE_BYTE]); + const key = tools.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = new Uint8Array(splitPath.length * 4); + value.set(data.masterFingerprint, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + tools.writeUInt32(value, offset, num, 'LE'); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; }'; + function check(data) { + return ( + data.pubkey instanceof Uint8Array && + data.masterFingerprint instanceof Uint8Array && + typeof data.path === 'string' && + isValidPubkey(data.pubkey) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = tools.toHex(item.pubkey); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => tools.compare(v.pubkey, item.pubkey) === 0).length === 0 + ); + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.d.ts new file mode 100644 index 0000000..0966a06 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.d.ts @@ -0,0 +1,2 @@ +import { KeyValue } from '../../interfaces'; +export declare function makeChecker(pubkeyTypes: number[]): (keyVal: KeyValue) => Uint8Array | undefined; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.js new file mode 100644 index 0000000..6ffd454 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/checkPubkey.js @@ -0,0 +1,19 @@ +import * as tools from 'uint8array-tools'; +export function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + tools.toHex(keyVal.key), + ); + } + } + return pubkey; + } +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.d.ts new file mode 100644 index 0000000..fa1f0d8 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.d.ts @@ -0,0 +1,8 @@ +import { KeyValue, RedeemScript } from '../../interfaces'; +export declare function makeConverter(TYPE_BYTE: number): { + decode: (keyVal: KeyValue) => RedeemScript; + encode: (data: RedeemScript) => KeyValue; + check: (data: any) => data is RedeemScript; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.js new file mode 100644 index 0000000..8e64416 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/redeemScript.js @@ -0,0 +1,33 @@ +import * as tools from 'uint8array-tools'; +export function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Uint8Array.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array; + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.d.ts new file mode 100644 index 0000000..ef42ca9 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.d.ts @@ -0,0 +1,8 @@ +import { KeyValue, TapBip32Derivation } from '../../interfaces'; +export declare function makeConverter(TYPE_BYTE: number): { + decode: (keyVal: KeyValue) => TapBip32Derivation; + encode: (data: TapBip32Derivation) => KeyValue; + check: (data: any) => data is TapBip32Derivation; + expected: string; + canAddToArray: (array: TapBip32Derivation[], item: TapBip32Derivation, dupeSet: Set) => boolean; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.js new file mode 100644 index 0000000..b25bbe7 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapBip32Derivation.js @@ -0,0 +1,52 @@ +import * as varuint from 'varuint-bitcoin'; +import * as tools from 'uint8array-tools'; +import * as bip32Derivation from './bip32Derivation.js'; +const isValidBIP340Key = pubkey => pubkey.length === 32; +export function makeConverter(TYPE_BYTE) { + const parent = bip32Derivation.makeConverter(TYPE_BYTE, isValidBIP340Key); + function decode(keyVal) { + const { numberValue: nHashes, bytes: nHashesLen } = varuint.decode( + keyVal.value, + ); + const base = parent.decode({ + key: keyVal.key, + value: keyVal.value.slice(nHashesLen + Number(nHashes) * 32), + }); + const leafHashes = new Array(Number(nHashes)); + for (let i = 0, _offset = nHashesLen; i < nHashes; i++, _offset += 32) { + leafHashes[i] = keyVal.value.slice(_offset, _offset + 32); + } + return { ...base, leafHashes }; + } + function encode(data) { + const base = parent.encode(data); + const nHashesLen = varuint.encodingLength(data.leafHashes.length); + const nHashesBuf = new Uint8Array(nHashesLen); + varuint.encode(data.leafHashes.length, nHashesBuf); + const value = tools.concat([nHashesBuf, ...data.leafHashes, base.value]); + return { ...base, value }; + } + const expected = + '{ ' + + 'masterFingerprint: Uint8Array; ' + + 'pubkey: Uint8Array; ' + + 'path: string; ' + + 'leafHashes: Uint8Array[]; ' + + '}'; + function check(data) { + return ( + Array.isArray(data.leafHashes) && + data.leafHashes.every( + leafHash => leafHash instanceof Uint8Array && leafHash.length === 32, + ) && + parent.check(data) + ); + } + return { + decode, + encode, + check, + expected, + canAddToArray: parent.canAddToArray, + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.d.ts new file mode 100644 index 0000000..30e5e4f --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.d.ts @@ -0,0 +1,8 @@ +import { KeyValue, TapInternalKey } from '../../interfaces'; +export declare function makeConverter(TYPE_BYTE: number): { + decode: (keyVal: KeyValue) => TapInternalKey; + encode: (data: TapInternalKey) => KeyValue; + check: (data: any) => data is TapInternalKey; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.js new file mode 100644 index 0000000..252af20 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/tapInternalKey.js @@ -0,0 +1,37 @@ +import * as tools from 'uint8array-tools'; +export function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapInternalKey with key 0x' + + tools.toHex(keyVal.key), + ); + } + if (keyVal.value.length !== 32) { + throw new Error( + 'Decode Error: tapInternalKey not a 32-byte x-only pubkey', + ); + } + return keyVal.value; + } + function encode(value) { + const key = Uint8Array.from([TYPE_BYTE]); + return { key, value }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array && data.length === 32; + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.tapInternalKey === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.d.ts new file mode 100644 index 0000000..809c322 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.d.ts @@ -0,0 +1,8 @@ +import { KeyValue, WitnessScript } from '../../interfaces'; +export declare function makeConverter(TYPE_BYTE: number): { + decode: (keyVal: KeyValue) => WitnessScript; + encode: (data: WitnessScript) => KeyValue; + check: (data: any) => data is WitnessScript; + expected: string; + canAdd: (currentData: any, newData: any) => boolean; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.js new file mode 100644 index 0000000..0a18693 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/shared/witnessScript.js @@ -0,0 +1,35 @@ +import * as tools from 'uint8array-tools'; +export function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + tools.toHex(keyVal.key), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Uint8Array.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Uint8Array'; + function check(data) { + return data instanceof Uint8Array; + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.d.ts new file mode 100644 index 0000000..0fbb8a6 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.d.ts @@ -0,0 +1,5 @@ +import { KeyValue } from '../interfaces'; +export declare const range: (n: number) => number[]; +export declare function reverseBuffer(buffer: Uint8Array): Uint8Array; +export declare function keyValsToBuffer(keyVals: KeyValue[]): Uint8Array; +export declare function keyValToBuffer(keyVal: KeyValue): Uint8Array; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.js b/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.js new file mode 100644 index 0000000..3e39cc1 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/converter/tools.js @@ -0,0 +1,32 @@ +import * as varuint from 'varuint-bitcoin'; +import * as tools from 'uint8array-tools'; +export const range = n => [...Array(n).keys()]; +export function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +export function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Uint8Array.from([0])); + return tools.concat(buffers); +} +export function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint.encodingLength(keyLen); + const valVarIntLen = varuint.encodingLength(valLen); + const buffer = new Uint8Array(keyVarIntLen + keyLen + valVarIntLen + valLen); + varuint.encode(keyLen, buffer, 0); + buffer.set(keyVal.key, keyVarIntLen); + varuint.encode(valLen, buffer, keyVarIntLen + keyLen); + buffer.set(keyVal.value, keyVarIntLen + keyLen + valVarIntLen); + return buffer; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/interfaces.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/interfaces.d.ts new file mode 100644 index 0000000..9a5112e --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/interfaces.d.ts @@ -0,0 +1,114 @@ +export declare type TransactionFromBuffer = (buffer: Uint8Array) => Transaction; +export interface Transaction { + getInputOutputCounts(): { + inputCount: number; + outputCount: number; + }; + addInput(objectArg: any): void; + addOutput(objectArg: any): void; + toBuffer(): Uint8Array; +} +export interface KeyValue { + key: Uint8Array; + value: Uint8Array; +} +export interface PsbtGlobal extends PsbtGlobalUpdate { + unsignedTx: Transaction; + unknownKeyVals?: KeyValue[]; +} +export interface PsbtGlobalUpdate { + globalXpub?: GlobalXpub[]; +} +export interface PsbtInput extends PsbtInputUpdate { + unknownKeyVals?: KeyValue[]; +} +export interface PsbtInputUpdate { + partialSig?: PartialSig[]; + nonWitnessUtxo?: NonWitnessUtxo; + witnessUtxo?: WitnessUtxo; + sighashType?: SighashType; + redeemScript?: RedeemScript; + witnessScript?: WitnessScript; + bip32Derivation?: Bip32Derivation[]; + finalScriptSig?: FinalScriptSig; + finalScriptWitness?: FinalScriptWitness; + porCommitment?: PorCommitment; + tapKeySig?: TapKeySig; + tapScriptSig?: TapScriptSig[]; + tapLeafScript?: TapLeafScript[]; + tapBip32Derivation?: TapBip32Derivation[]; + tapInternalKey?: TapInternalKey; + tapMerkleRoot?: TapMerkleRoot; +} +export interface PsbtInputExtended extends PsbtInput { + [index: string]: any; +} +export interface PsbtOutput extends PsbtOutputUpdate { + unknownKeyVals?: KeyValue[]; +} +export interface PsbtOutputUpdate { + redeemScript?: RedeemScript; + witnessScript?: WitnessScript; + bip32Derivation?: Bip32Derivation[]; + tapBip32Derivation?: TapBip32Derivation[]; + tapTree?: TapTree; + tapInternalKey?: TapInternalKey; +} +export interface PsbtOutputExtended extends PsbtOutput { + [index: string]: any; +} +export interface GlobalXpub { + extendedPubkey: Uint8Array; + masterFingerprint: Uint8Array; + path: string; +} +export interface PartialSig { + pubkey: Uint8Array; + signature: Uint8Array; +} +export interface Bip32Derivation { + masterFingerprint: Uint8Array; + pubkey: Uint8Array; + path: string; +} +export interface WitnessUtxo { + script: Uint8Array; + value: bigint; +} +export declare type NonWitnessUtxo = Uint8Array; +export declare type SighashType = number; +export declare type RedeemScript = Uint8Array; +export declare type WitnessScript = Uint8Array; +export declare type FinalScriptSig = Uint8Array; +export declare type FinalScriptWitness = Uint8Array; +export declare type PorCommitment = string; +export declare type TapKeySig = Uint8Array; +export interface TapScriptSig extends PartialSig { + leafHash: Uint8Array; +} +interface TapScript { + leafVersion: number; + script: Uint8Array; +} +export declare type ControlBlock = Uint8Array; +export interface TapLeafScript extends TapScript { + controlBlock: ControlBlock; +} +export interface TapBip32Derivation extends Bip32Derivation { + leafHashes: Uint8Array[]; +} +export declare type TapInternalKey = Uint8Array; +export declare type TapMerkleRoot = Uint8Array; +export interface TapLeaf extends TapScript { + depth: number; +} +export interface TapTree { + leaves: TapLeaf[]; +} +export declare type TransactionIOCountGetter = (txBuffer: Uint8Array) => { + inputCount: number; + outputCount: number; +}; +export declare type TransactionVersionSetter = (version: number, txBuffer: Uint8Array) => Uint8Array; +export declare type TransactionLocktimeSetter = (locktime: number, txBuffer: Uint8Array) => Uint8Array; +export {}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/interfaces.js b/src/libMPC/node_modules/bip174/src/esm/lib/interfaces.js new file mode 100644 index 0000000..e69de29 diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.d.ts new file mode 100644 index 0000000..f59bc3b --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.d.ts @@ -0,0 +1,11 @@ +import { KeyValue, Transaction, TransactionFromBuffer } from '../interfaces'; +import { PsbtAttributes } from './index.js'; +export declare function psbtFromBuffer(buffer: Uint8Array, txGetter: TransactionFromBuffer): PsbtAttributes; +interface PsbtFromKeyValsArg { + globalMapKeyVals: KeyValue[]; + inputKeyVals: KeyValue[][]; + outputKeyVals: KeyValue[][]; +} +export declare function checkKeyBuffer(type: string, keyBuf: Uint8Array, keyNum: number): void; +export declare function psbtFromKeyVals(unsignedTx: Transaction, { globalMapKeyVals, inputKeyVals, outputKeyVals }: PsbtFromKeyValsArg): PsbtAttributes; +export {}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.js b/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.js new file mode 100644 index 0000000..1df0911 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/fromBuffer.js @@ -0,0 +1,329 @@ +import * as convert from '../converter/index.js'; +import { range } from '../converter/tools.js'; +import * as varuint from 'varuint-bitcoin'; +import * as tools from 'uint8array-tools'; +import { GlobalTypes, InputTypes, OutputTypes } from '../typeFields.js'; +export function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const { numberValue: keyLen, bytes } = varuint.decode(buffer, offset); + offset += bytes; + const key = buffer.slice(offset, offset + Number(keyLen)); + offset += Number(keyLen); + return key; + } + function readUInt32BE() { + const num = tools.readUInt32(buffer, offset, 'BE'); + offset += 4; + return num; + } + function readUInt8() { + const num = tools.readUInt8(buffer, offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = tools.readUInt8(buffer, offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = tools.toHex(keyVal.key); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); +} +export function checkKeyBuffer(type, keyBuf, keyNum) { + if (tools.compare(keyBuf, Uint8Array.from([keyNum]))) { + throw new Error( + // `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + `Format Error: Invalid ${type} key: ${tools.toHex(keyBuf)}`, + ); + } +} +export function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, +) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case GlobalTypes.UNSIGNED_TX: + checkKeyBuffer('global', keyVal.key, GlobalTypes.UNSIGNED_TX); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer('input', keyVal.key, InputTypes.NON_WITNESS_UTXO); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert.inputs.nonWitnessUtxo.decode(keyVal); + break; + case InputTypes.WITNESS_UTXO: + checkKeyBuffer('input', keyVal.key, InputTypes.WITNESS_UTXO); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert.inputs.witnessUtxo.decode(keyVal); + break; + case InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert.inputs.partialSig.decode(keyVal)); + break; + case InputTypes.SIGHASH_TYPE: + checkKeyBuffer('input', keyVal.key, InputTypes.SIGHASH_TYPE); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert.inputs.sighashType.decode(keyVal); + break; + case InputTypes.REDEEM_SCRIPT: + checkKeyBuffer('input', keyVal.key, InputTypes.REDEEM_SCRIPT); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert.inputs.redeemScript.decode(keyVal); + break; + case InputTypes.WITNESS_SCRIPT: + checkKeyBuffer('input', keyVal.key, InputTypes.WITNESS_SCRIPT); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert.inputs.witnessScript.decode(keyVal); + break; + case InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert.inputs.bip32Derivation.decode(keyVal), + ); + break; + case InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer('input', keyVal.key, InputTypes.FINAL_SCRIPTSIG); + input.finalScriptSig = convert.inputs.finalScriptSig.decode(keyVal); + break; + case InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer('input', keyVal.key, InputTypes.FINAL_SCRIPTWITNESS); + input.finalScriptWitness = convert.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case InputTypes.POR_COMMITMENT: + checkKeyBuffer('input', keyVal.key, InputTypes.POR_COMMITMENT); + input.porCommitment = convert.inputs.porCommitment.decode(keyVal); + break; + case InputTypes.TAP_KEY_SIG: + checkKeyBuffer('input', keyVal.key, InputTypes.TAP_KEY_SIG); + input.tapKeySig = convert.inputs.tapKeySig.decode(keyVal); + break; + case InputTypes.TAP_SCRIPT_SIG: + if (input.tapScriptSig === undefined) { + input.tapScriptSig = []; + } + input.tapScriptSig.push(convert.inputs.tapScriptSig.decode(keyVal)); + break; + case InputTypes.TAP_LEAF_SCRIPT: + if (input.tapLeafScript === undefined) { + input.tapLeafScript = []; + } + input.tapLeafScript.push(convert.inputs.tapLeafScript.decode(keyVal)); + break; + case InputTypes.TAP_BIP32_DERIVATION: + if (input.tapBip32Derivation === undefined) { + input.tapBip32Derivation = []; + } + input.tapBip32Derivation.push( + convert.inputs.tapBip32Derivation.decode(keyVal), + ); + break; + case InputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer('input', keyVal.key, InputTypes.TAP_INTERNAL_KEY); + input.tapInternalKey = convert.inputs.tapInternalKey.decode(keyVal); + break; + case InputTypes.TAP_MERKLE_ROOT: + checkKeyBuffer('input', keyVal.key, InputTypes.TAP_MERKLE_ROOT); + input.tapMerkleRoot = convert.inputs.tapMerkleRoot.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer('output', keyVal.key, OutputTypes.REDEEM_SCRIPT); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert.outputs.redeemScript.decode(keyVal); + break; + case OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer('output', keyVal.key, OutputTypes.WITNESS_SCRIPT); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert.outputs.witnessScript.decode(keyVal); + break; + case OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert.outputs.bip32Derivation.decode(keyVal), + ); + break; + case OutputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer('output', keyVal.key, OutputTypes.TAP_INTERNAL_KEY); + output.tapInternalKey = convert.outputs.tapInternalKey.decode(keyVal); + break; + case OutputTypes.TAP_TREE: + checkKeyBuffer('output', keyVal.key, OutputTypes.TAP_TREE); + output.tapTree = convert.outputs.tapTree.decode(keyVal); + break; + case OutputTypes.TAP_BIP32_DERIVATION: + if (output.tapBip32Derivation === undefined) { + output.tapBip32Derivation = []; + } + output.tapBip32Derivation.push( + convert.outputs.tapBip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.d.ts new file mode 100644 index 0000000..bbd9eae --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.d.ts @@ -0,0 +1,8 @@ +import { PsbtGlobal, PsbtInput, PsbtOutput } from '../interfaces'; +export * from './fromBuffer.js'; +export * from './toBuffer.js'; +export interface PsbtAttributes { + globalMap: PsbtGlobal; + inputs: PsbtInput[]; + outputs: PsbtOutput[]; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.js b/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.js new file mode 100644 index 0000000..b16096c --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/index.js @@ -0,0 +1,2 @@ +export * from './fromBuffer.js'; +export * from './toBuffer.js'; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.d.ts new file mode 100644 index 0000000..4e7b230 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.d.ts @@ -0,0 +1,8 @@ +import { KeyValue } from '../interfaces'; +import { PsbtAttributes } from './index.js'; +export declare function psbtToBuffer({ globalMap, inputs, outputs, }: PsbtAttributes): Uint8Array; +export declare function psbtToKeyVals({ globalMap, inputs, outputs, }: PsbtAttributes): { + globalKeyVals: KeyValue[]; + inputKeyVals: KeyValue[][]; + outputKeyVals: KeyValue[][]; +}; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.js b/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.js new file mode 100644 index 0000000..054c654 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/parser/toBuffer.js @@ -0,0 +1,61 @@ +import * as convert from '../converter/index.js'; +import { keyValsToBuffer } from '../converter/tools.js'; +import * as tools from 'uint8array-tools'; +export function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Uint8Array.from([0])] + : keyVals.map(keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = new Uint8Array(5); + header.set([0x70, 0x73, 0x62, 0x74, 0xff], 0); + return tools.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); +} +const sortKeyVals = (a, b) => { + return tools.compare(a.key, b.key); +}; +function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => tools.toHex(kv.key)); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(tools.toHex(keyVal.key)); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); +} +export function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; +} diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/psbt.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/psbt.d.ts new file mode 100644 index 0000000..48bd057 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/psbt.d.ts @@ -0,0 +1,26 @@ +import { KeyValue, PsbtGlobal, PsbtGlobalUpdate, PsbtInput, PsbtInputExtended, PsbtInputUpdate, PsbtOutput, PsbtOutputExtended, PsbtOutputUpdate, Transaction, TransactionFromBuffer } from './interfaces.js'; +export declare class Psbt { + static fromBase64(this: T, data: string, txFromBuffer: TransactionFromBuffer): InstanceType; + static fromHex(this: T, data: string, txFromBuffer: TransactionFromBuffer): InstanceType; + static fromBuffer(this: T, buffer: Uint8Array, txFromBuffer: TransactionFromBuffer): InstanceType; + readonly inputs: PsbtInput[]; + readonly outputs: PsbtOutput[]; + readonly globalMap: PsbtGlobal; + constructor(tx: Transaction); + toBase64(): string; + toHex(): string; + toBuffer(): Uint8Array; + updateGlobal(updateData: PsbtGlobalUpdate): this; + updateInput(inputIndex: number, updateData: PsbtInputUpdate): this; + updateOutput(outputIndex: number, updateData: PsbtOutputUpdate): this; + addUnknownKeyValToGlobal(keyVal: KeyValue): this; + addUnknownKeyValToInput(inputIndex: number, keyVal: KeyValue): this; + addUnknownKeyValToOutput(outputIndex: number, keyVal: KeyValue): this; + addInput(inputData: PsbtInputExtended): this; + addOutput(outputData: PsbtOutputExtended): this; + clearFinalizedInput(inputIndex: number): this; + combine(...those: this[]): this; + getTransaction(): Uint8Array; +} +export { Bip32Derivation, NonWitnessUtxo, ControlBlock, FinalScriptSig, FinalScriptWitness, GlobalXpub, KeyValue, PartialSig, PorCommitment, PsbtGlobal, PsbtGlobalUpdate, PsbtInput, PsbtInputExtended, PsbtInputUpdate, PsbtOutput, PsbtOutputExtended, PsbtOutputUpdate, RedeemScript, SighashType, TapBip32Derivation, TapInternalKey, TapKeySig, TapLeaf, TapLeafScript, TapMerkleRoot, TapScriptSig, TapTree, Transaction, TransactionFromBuffer, TransactionIOCountGetter, TransactionLocktimeSetter, TransactionVersionSetter, WitnessScript, WitnessUtxo, } from './interfaces.js'; +export { checkForInput, checkForOutput } from './utils.js'; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/psbt.js b/src/libMPC/node_modules/bip174/src/esm/lib/psbt.js new file mode 100644 index 0000000..88cc3ba --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/psbt.js @@ -0,0 +1,150 @@ +import { combine } from './combiner/index.js'; +import { psbtFromBuffer, psbtToBuffer } from './parser/index.js'; +import { GlobalTypes, InputTypes, OutputTypes } from './typeFields.js'; +import { + addInputAttributes, + addOutputAttributes, + checkForInput, + checkForOutput, + checkHasKey, + getEnumLength, + inputCheckUncleanFinalized, + updateGlobal, + updateInput, + updateOutput, +} from './utils.js'; +import * as tools from 'uint8array-tools'; +export class Psbt { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = tools.fromBase64(data); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = tools.fromHex(data); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return tools.toBase64(buffer); + } + toHex() { + const buffer = this.toBuffer(); + return tools.toHex(buffer); + } + toBuffer() { + return psbtToBuffer(this); + } + updateGlobal(updateData) { + updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = checkForInput(this.inputs, inputIndex); + updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = checkForOutput(this.outputs, outputIndex); + updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + getEnumLength(GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = checkForInput(this.inputs, inputIndex); + checkHasKey(keyVal, input.unknownKeyVals, getEnumLength(InputTypes)); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = checkForOutput(this.outputs, outputIndex); + checkHasKey(keyVal, output.unknownKeyVals, getEnumLength(OutputTypes)); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToOutput(outputIndex, keyVal), + ); + addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = checkForInput(this.inputs, inputIndex); + inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } +} +export { checkForInput, checkForOutput } from './utils.js'; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.d.ts new file mode 100644 index 0000000..e8cbcbe --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.d.ts @@ -0,0 +1,33 @@ +export declare enum GlobalTypes { + UNSIGNED_TX = 0, + GLOBAL_XPUB = 1 +} +export declare const GLOBAL_TYPE_NAMES: string[]; +export declare enum InputTypes { + NON_WITNESS_UTXO = 0, + WITNESS_UTXO = 1, + PARTIAL_SIG = 2, + SIGHASH_TYPE = 3, + REDEEM_SCRIPT = 4, + WITNESS_SCRIPT = 5, + BIP32_DERIVATION = 6, + FINAL_SCRIPTSIG = 7, + FINAL_SCRIPTWITNESS = 8, + POR_COMMITMENT = 9, + TAP_KEY_SIG = 19, + TAP_SCRIPT_SIG = 20, + TAP_LEAF_SCRIPT = 21, + TAP_BIP32_DERIVATION = 22, + TAP_INTERNAL_KEY = 23, + TAP_MERKLE_ROOT = 24 +} +export declare const INPUT_TYPE_NAMES: string[]; +export declare enum OutputTypes { + REDEEM_SCRIPT = 0, + WITNESS_SCRIPT = 1, + BIP32_DERIVATION = 2, + TAP_INTERNAL_KEY = 5, + TAP_TREE = 6, + TAP_BIP32_DERIVATION = 7 +} +export declare const OUTPUT_TYPE_NAMES: string[]; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.js b/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.js new file mode 100644 index 0000000..23cc1e3 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/typeFields.js @@ -0,0 +1,62 @@ +export var GlobalTypes; +(function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; +})(GlobalTypes || (GlobalTypes = {})); +export const GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; +export var InputTypes; +(function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + InputTypes[(InputTypes['TAP_KEY_SIG'] = 19)] = 'TAP_KEY_SIG'; + InputTypes[(InputTypes['TAP_SCRIPT_SIG'] = 20)] = 'TAP_SCRIPT_SIG'; + InputTypes[(InputTypes['TAP_LEAF_SCRIPT'] = 21)] = 'TAP_LEAF_SCRIPT'; + InputTypes[(InputTypes['TAP_BIP32_DERIVATION'] = 22)] = + 'TAP_BIP32_DERIVATION'; + InputTypes[(InputTypes['TAP_INTERNAL_KEY'] = 23)] = 'TAP_INTERNAL_KEY'; + InputTypes[(InputTypes['TAP_MERKLE_ROOT'] = 24)] = 'TAP_MERKLE_ROOT'; +})(InputTypes || (InputTypes = {})); +export const INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + 'tapKeySig', + 'tapScriptSig', + 'tapLeafScript', + 'tapBip32Derivation', + 'tapInternalKey', + 'tapMerkleRoot', +]; +export var OutputTypes; +(function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + OutputTypes[(OutputTypes['TAP_INTERNAL_KEY'] = 5)] = 'TAP_INTERNAL_KEY'; + OutputTypes[(OutputTypes['TAP_TREE'] = 6)] = 'TAP_TREE'; + OutputTypes[(OutputTypes['TAP_BIP32_DERIVATION'] = 7)] = + 'TAP_BIP32_DERIVATION'; +})(OutputTypes || (OutputTypes = {})); +export const OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'tapInternalKey', + 'tapTree', + 'tapBip32Derivation', +]; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/utils.d.ts b/src/libMPC/node_modules/bip174/src/esm/lib/utils.d.ts new file mode 100644 index 0000000..40f5e34 --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/utils.d.ts @@ -0,0 +1,13 @@ +import { KeyValue, PsbtGlobal, PsbtGlobalUpdate, PsbtInput, PsbtInputUpdate, PsbtOutput, PsbtOutputUpdate } from './interfaces.js'; +export declare function checkForInput(inputs: PsbtInput[], inputIndex: number): PsbtInput; +export declare function checkForOutput(outputs: PsbtOutput[], outputIndex: number): PsbtOutput; +export declare function checkHasKey(checkKeyVal: KeyValue, keyVals: KeyValue[] | undefined, enumLength: number): void; +export declare function getEnumLength(myenum: any): number; +export declare function inputCheckUncleanFinalized(inputIndex: number, input: PsbtInput): void; +export declare const updateGlobal: (updateData: PsbtGlobalUpdate, mainData: PsbtGlobal) => void; +export declare const updateInput: (updateData: PsbtInputUpdate, mainData: PsbtInput) => void; +export declare const updateOutput: (updateData: PsbtOutputUpdate, mainData: PsbtOutput) => void; +export declare function addInputAttributes(inputs: PsbtInput[], data: any): void; +export declare function addOutputAttributes(outputs: PsbtOutput[], data: any): void; +export declare function defaultVersionSetter(version: number, txBuf: Uint8Array): Uint8Array; +export declare function defaultLocktimeSetter(locktime: number, txBuf: Uint8Array): Uint8Array; diff --git a/src/libMPC/node_modules/bip174/src/esm/lib/utils.js b/src/libMPC/node_modules/bip174/src/esm/lib/utils.js new file mode 100644 index 0000000..70acaab --- /dev/null +++ b/src/libMPC/node_modules/bip174/src/esm/lib/utils.js @@ -0,0 +1,130 @@ +import * as converter from './converter/index.js'; +import * as tools from 'uint8array-tools'; +export function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; +} +export function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; +} +export function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => tools.compare(kv.key, checkKeyVal.key) === 0) + .length !== 0 + ) { + throw new Error(`Duplicate Key: ${tools.toHex(checkKeyVal.key)}`); + } +} +export function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; +} +export function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } +} +function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); +} +function updateMaker(typeName) { + return (updateData, mainData) => { + // @ts-ignore + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; +} +export const updateGlobal = updateMaker('global'); +export const updateInput = updateMaker('input'); +export const updateOutput = updateMaker('output'); +export function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + updateInput(data, input); +} +export function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForOutput(outputs, index); + updateOutput(data, output); +} +export function defaultVersionSetter(version, txBuf) { + if (!(txBuf instanceof Uint8Array) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + tools.writeUInt32(txBuf, 0, version, 'LE'); + return txBuf; +} +export function defaultLocktimeSetter(locktime, txBuf) { + if (!(txBuf instanceof Uint8Array) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + tools.writeUInt32(txBuf, txBuf.length - 4, locktime, 'LE'); + return txBuf; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/LICENSE b/src/libMPC/node_modules/bitcoinjs-lib/LICENSE new file mode 100644 index 0000000..0383ebc --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011-2020 bitcoinjs-lib 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. diff --git a/src/libMPC/node_modules/bitcoinjs-lib/README.md b/src/libMPC/node_modules/bitcoinjs-lib/README.md new file mode 100644 index 0000000..ae762f5 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/README.md @@ -0,0 +1,209 @@ +BitcoinJS kawaii logo + +(Logo by [@sawaratsuki1004](https://x.com/sawaratsuki1004)) + +([LICENSE for the logo is on SAWARATSUKI Github repo](https://github.com/SAWARATSUKI/KawaiiLogos/blob/main/README_EN.md)) + +[![Github CI](https://github.com/bitcoinjs/bitcoinjs-lib/actions/workflows/main_ci.yml/badge.svg)](https://github.com/bitcoinjs/bitcoinjs-lib/actions/workflows/main_ci.yml) [![NPM](https://img.shields.io/npm/v/bitcoinjs-lib.svg)](https://www.npmjs.org/package/bitcoinjs-lib) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) + +A javascript Bitcoin library for node.js and browsers. Written in TypeScript, but committing the JS files to verify. + +Released under the terms of the [MIT LICENSE](LICENSE). + +## Should I use this in production? +If you are thinking of using the *master* branch of this library in production, **stop**. +Master is not stable; it is our development branch, and [only tagged releases may be classified as stable](https://github.com/bitcoinjs/bitcoinjs-lib/tags). + +## Can I trust this code? +> Don't trust. Verify. + +We recommend every user of this library and the [bitcoinjs](https://github.com/bitcoinjs) ecosystem audit and verify any underlying code for its validity and suitability, including reviewing any and all of your project's dependencies. + +Mistakes and bugs happen, but with your help in resolving and reporting [issues](https://github.com/bitcoinjs/bitcoinjs-lib/issues), together we can produce open source software that is: + +- Easy to audit and verify, +- Tested, with test coverage >95%, +- Advanced and feature rich, +- Standardized, using [prettier](https://github.com/prettier/prettier) and Node `Buffer`'s throughout, and +- Friendly, with a strong and helpful community, ready to answer questions. + +## Documentation +Visit our [documentation](https://bitcoinjs.github.io/bitcoinjs-lib/) to explore the available resources. We're continually enhancing our documentation with additional features for an enriched experience. If you need further guidance beyond what our [examples](#examples) offer, don't hesitate to [ask for help](https://github.com/bitcoinjs/bitcoinjs-lib/issues/new). We're here to assist you. + +You can find a [Web UI](https://bitcoincore.tech/apps/bitcoinjs-ui/index.html) that covers most of the `psbt.ts`, `transaction.ts` and `p2*.ts` APIs [here](https://bitcoincore.tech/apps/bitcoinjs-ui/index.html). + +## How can I contact the developers outside of Github? +**Most of the time, this is not appropriate. Creating issues and pull requests in the open will help others with similar issues, so please try to use public issues and pull requests for communication.** + +That said, sometimes developers might be open to taking things off the record (ie. You want to share code that you don't want public to get help with it). In that case, please negotiate on the public issues as to where you will contact. + +We have created public rooms on IRC (`#bitcoinjs` on `libera.chat`) and Matrix (`#bitcoinjs-dev:matrix.org`). These two channels have been joined together in a Matrix "Space" which has the Matrix room AND an IRC bridge room that can converse with the IRC room. The "Space" is `#bitcoinjs-space:matrix.org`. + +Matrix and IRC both have functions for direct messaging, but IRC is not end to end encrypted, so Matrix is recommended for most communication. The official Matrix client maintained by the Matrix core team is called "Element" and can be downloaded here: https://element.io/download (Account creation is free on the matrix.org server, which is the default setting for Element.) + +We used to have a Slack. It is dead. If you find it, no one will answer you most likely. + +No we will not make a Discord. + +## Installation +``` bash +npm install bitcoinjs-lib +# optionally, install a key derivation library as well +npm install ecpair bip32 +# ecpair is the ECPair class for single keys +# bip32 is for generating HD keys +``` + +Previous versions of the library included classes for key management (ECPair, HDNode(->"bip32")) but now these have been separated into different libraries. This lowers the bundle size significantly if you don't need to perform any crypto functions (converting private to public keys and deriving HD keys). + +Typically we support the [Node Maintenance LTS version](https://github.com/nodejs/Release). TypeScript target will be set +to the ECMAScript version in which all features are fully supported by current Active Node LTS. +However, depending on adoption among other environments (browsers etc.) we may keep the target back a year or two. +If in doubt, see the [main_ci.yml](.github/workflows/main_ci.yml) for what versions are used by our continuous integration tests. + +**WARNING**: We presently don't provide any tooling to verify that the release on `npm` matches GitHub. As such, you should verify anything downloaded by `npm` against your own verified copy. + + +## Usage +Crypto is hard. + +When working with private keys, the random number generator is fundamentally one of the most important parts of any software you write. +For random number generation, we *default* to the [`randombytes`](https://github.com/crypto-browserify/randombytes) module, which uses [`window.crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues) in the browser, or Node js' [`crypto.randomBytes`](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback), depending on your build system. +Although this default is ~OK, there is no simple way to detect if the underlying RNG provided is good enough, or if it is **catastrophically bad**. +You should always verify this yourself to your own standards. + +This library uses [tiny-secp256k1](https://github.com/bitcoinjs/tiny-secp256k1), which uses [RFC6979](https://tools.ietf.org/html/rfc6979) to help prevent `k` re-use and exploitation. +Unfortunately, this isn't a silver bullet. +Often, Javascript itself is working against us by bypassing these counter-measures. + +Problems in [`Buffer (UInt8Array)`](https://github.com/feross/buffer), for example, can trivially result in **catastrophic fund loss** without any warning. +It can do this through undermining your random number generation, accidentally producing a [duplicate `k` value](https://www.nilsschneider.net/2013/01/28/recovering-bitcoin-private-keys.html), sending Bitcoin to a malformed output script, or any of a million different ways. +Running tests in your target environment is important and a recommended step to verify continuously. + +Finally, **adhere to best practice**. +We are not an authoritative source of best practice, but, at the very least: + +* [Don't reuse addresses](https://en.bitcoin.it/wiki/Address_reuse). +* Don't share BIP32 extended public keys ('xpubs'). [They are a liability](https://bitcoin.stackexchange.com/questions/56916/derivation-of-parent-private-key-from-non-hardened-child), and it only takes 1 misplaced private key (or a buggy implementation!) and you are vulnerable to **catastrophic fund loss**. +* [Don't use `Math.random`](https://security.stackexchange.com/questions/181580/why-is-math-random-not-designed-to-be-cryptographically-secure) - in any way - don't. +* Enforce that users always verify (manually) a freshly-decoded human-readable version of their intended transaction before broadcast. +* [Don't *ask* users to generate mnemonics](https://en.bitcoin.it/wiki/Brainwallet#cite_note-1), or 'brain wallets', humans are terrible random number generators. +* Lastly, if you can, use [Typescript](https://www.typescriptlang.org/) or similar. + + +### Browser +The recommended method of using `bitcoinjs-lib` in your browser is through [browserify](http://browserify.org/). + +If you'd like to use a different (more modern) build tool than `browserify`, you can compile just this library and its dependencies into a single JavaScript file: + +```sh +$ npm install bitcoinjs-lib browserify +$ npx browserify --standalone bitcoin -o bitcoinjs-lib.js <<< "module.exports = require('bitcoinjs-lib');" +``` + +Which you can then import as an ESM module: + +```javascript + +```` + +#### Using Taproot: +When utilizing Taproot features with bitcoinjs-lib, you may need to include an additional ECC (Elliptic Curve Cryptography) library. The commonly used `tiny-secp256k1` library, however, might lead to compatibility issues due to its reliance on WASM (WebAssembly). The following alternatives may be used instead, though they may be significantly slower for high volume of signing and pubkey deriving operations. + +#### Alternatives for ECC Library: +1. `@bitcoinjs-lib/tiny-secp256k1-asmjs` + A version of `tiny-secp256k1` compiled to ASM.js directly from the WASM version, potentially better supported in browsers. This is the slowest option. +2. `@bitcoinerlab/secp256k1` + Another alternative library for ECC functionality. This requires access to the global `BigInt` primitive. +For advantages and detailed comparison of these libraries, visit: [tiny-secp256k1 GitHub page](https://github.com/bitcoinjs/tiny-secp256k1). + +**NOTE**: We use Node Maintenance LTS features, if you need strict ES5, use [`--transform babelify`](https://github.com/babel/babelify) in conjunction with your `browserify` step (using an [`es2015`](https://babeljs.io/docs/plugins/preset-es2015/) preset). + +**WARNING**: iOS devices have [problems](https://github.com/feross/buffer/issues/136), use at least [buffer@5.0.5](https://github.com/feross/buffer/pull/155) or greater, and enforce the test suites (for `Buffer`, and any other dependency) pass before use. + +### Typescript or VSCode users +Type declarations for Typescript are included in this library. Normal installation should include all the needed type information. + +## Examples +The below examples are implemented as integration tests, they should be very easy to understand. +Otherwise, pull requests are appreciated. +Some examples interact (via HTTPS) with a 3rd Party Blockchain Provider (3PBP). + + +- [Taproot Key Spend](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts) +- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSIG](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts) +- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSEQUENCEVERIFY](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts) +- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSIGADD (3-of-3)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts) +- [Generate a random address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Import an address via WIF](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a 2-of-3 P2SH multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a SegWit address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a SegWit P2SH address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a SegWit 3-of-4 multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a SegWit 2-of-2 P2SH multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Support the retrieval of transactions for an address (3rd party blockchain)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a Testnet address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Generate a Litecoin address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts) +- [Create a 1-to-1 Transaction](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a typical Transaction](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with an OP\_RETURN output](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with a 2-of-4 P2SH(multisig) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with a SegWit P2SH(P2WPKH) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with a SegWit P2WPKH input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with a SegWit P2PK input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction with a SegWit 3-of-4 P2SH(P2WSH(multisig)) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction and sign with an HDSigner interface (bip32)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.spec.ts) +- [Import a BIP32 testnet xpriv and export to WIF](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Export a BIP32 xpriv, then import it](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Export a BIP32 xpub](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Create a BIP32, bitcoin, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Create a BIP44, bitcoin, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Create a BIP49, bitcoin testnet, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Use BIP39 to generate BIP32 addresses](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry (in the past)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry (in the future)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice and Bob can redeem the output at any time](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.spec.ts) +- [Create (but fail to broadcast via 3PBP) a Transaction where Alice attempts to redeem before the expiry](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry (in the future) (simple CHECKSEQUENCEVERIFY)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts) +- [Create (but fail to broadcast via 3PBP) a Transaction where Alice attempts to redeem before the expiry (simple CHECKSEQUENCEVERIFY)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Bob and Charles can send (complex CHECKSEQUENCEVERIFY)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice (mediator) and Bob can send after 2 blocks (complex CHECKSEQUENCEVERIFY)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts) +- [Create (and broadcast via 3PBP) a Transaction where Alice (mediator) can send after 5 blocks (complex CHECKSEQUENCEVERIFY)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts) + +If you have a use case that you feel could be listed here, please [ask for it](https://github.com/bitcoinjs/bitcoinjs-lib/issues/new)! + + +## Contributing +See [CONTRIBUTING.md](CONTRIBUTING.md). + + +### Running the test suite + +``` bash +npm test +npm run-script coverage +``` + +## Complementing Libraries +- [BIP21](https://github.com/bitcoinjs/bip21) - A BIP21 compatible URL encoding library +- [BIP38](https://github.com/bitcoinjs/bip38) - Passphrase-protected private keys +- [BIP39](https://github.com/bitcoinjs/bip39) - Mnemonic generation for deterministic keys +- [BIP32-Utils](https://github.com/bitcoinjs/bip32-utils) - A set of utilities for working with BIP32 +- [BIP66](https://github.com/bitcoinjs/bip66) - Strict DER signature decoding +- [BIP68](https://github.com/bitcoinjs/bip68) - Relative lock-time encoding library +- [BIP69](https://github.com/bitcoinjs/bip69) - Lexicographical Indexing of Transaction Inputs and Outputs +- [Base58](https://github.com/cryptocoinjs/bs58) - Base58 encoding/decoding +- [Base58 Check](https://github.com/bitcoinjs/bs58check) - Base58 check encoding/decoding +- [Bech32](https://github.com/bitcoinjs/bech32) - A BIP173/BIP350 compliant Bech32/Bech32m encoding library +- [coinselect](https://github.com/bitcoinjs/coinselect) - A fee-optimizing, transaction input selection module for bitcoinjs-lib. +- [merkle-lib](https://github.com/bitcoinjs/merkle-lib) - A performance conscious library for merkle root and tree calculations. +- [minimaldata](https://github.com/bitcoinjs/minimaldata) - A module to check bitcoin policy: SCRIPT_VERIFY_MINIMALDATA + + +## Alternatives +- [BCoin](https://github.com/indutny/bcoin) +- [Bitcore](https://github.com/bitpay/bitcore) +- [Cryptocoin](https://github.com/cryptocoinjs/cryptocoin) + + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/bitcoinjs-lib/package.json b/src/libMPC/node_modules/bitcoinjs-lib/package.json new file mode 100644 index 0000000..ca47758 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/package.json @@ -0,0 +1,113 @@ +{ + "name": "bitcoinjs-lib", + "version": "7.0.0-rc.0", + "description": "Client-side Bitcoin JavaScript library", + "type": "module", + "main": "./src/cjs/index.cjs", + "module": "./src/esm/index.js", + "types": "./src/cjs/index.d.ts", + "exports": { + ".": { + "require": "./src/cjs/index.cjs", + "import": "./src/esm/index.js", + "types": "./src/cjs/index.d.ts" + }, + "./src/*": { + "require": "./src/cjs/*.cjs", + "types": "./src/cjs/*.d.ts", + "import": "./src/esm/*.js" + } + }, + "engines": { + "node": ">=18.0.0" + }, + "keywords": [ + "bitcoinjs", + "bitcoin", + "browserify", + "javascript", + "bitcoinjs" + ], + "scripts": { + "audit": "better-npm-audit audit -l high", + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json && npm run formatjs", + "postbuild": "find src/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\; && chmod +x ./fixup.cjs && node fixup.cjs", + "clean": "rimraf src", + "coverage-report": "npm run build && npm run nobuild:coverage-report", + "coverage-html": "npm run build && npm run nobuild:coverage-html", + "coverage": "npm run build && npm run nobuild:coverage", + "doc": "typedoc", + "format": "npm run prettier -- --write", + "formatjs": "npm run prettierjs -- --write", + "format:ci": "npm run prettier -- --check && npm run prettierjs -- --check", + "gitdiff:ci": "npm run build && git diff --exit-code", + "integration": "npm run build && npm run nobuild:integration", + "lint": "eslint ts_src/** src/**/*.js", + "lint:tests": "eslint test/**/*.spec.ts", + "mocha:ts": "mocha --recursive", + "nobuild:coverage-report": "c8 report --reporter=lcov", + "nobuild:coverage-html": "c8 report --reporter=html", + "nobuild:coverage": "c8 --check-coverage --branches 85 --functions 90 --lines 90 npm run nobuild:unit", + "nobuild:integration": "npm run mocha:ts -- --timeout 50000 'test/integration/*.ts'", + "nobuild:unit": "npm run mocha:ts -- 'test/*.ts'", + "prettier": "prettier \"ts_src/**/*.ts\" \"test/**/*.ts\" --ignore-path ./.prettierignore", + "prettierjs": "prettier \"src/**/*.js\" --ignore-path ./.prettierignore", + "test": "npm run build && npm run format:ci && npm run lint && npm run nobuild:coverage", + "unit": "npm run build && npm run nobuild:unit" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/bitcoinjs-lib.git" + }, + "files": [ + "src" + ], + "dependencies": { + "@noble/hashes": "^1.2.0", + "bech32": "^2.0.0", + "bip174": "^3.0.0-rc.0", + "bs58check": "^4.0.0", + "uint8array-tools": "^0.0.9", + "valibot": "^0.38.0", + "varuint-bitcoin": "^2.0.0" + }, + "devDependencies": { + "bitcoinjs-lib": ".", + "@eslint/eslintrc": "^3.1.0", + "@eslint/js": "^9.9.1", + "@types/bs58": "^4.0.0", + "@types/bs58check": "^2.1.0", + "@types/mocha": "^5.2.7", + "@types/node": "^18.7.14", + "@types/proxyquire": "^1.3.28", + "@types/randombytes": "^2.0.0", + "@typescript-eslint/eslint-plugin": "^8.2.0", + "@typescript-eslint/parser": "^8.2.0", + "better-npm-audit": "^3.7.3", + "bip32": "^5.0.0-rc.0", + "bip39": "^3.1.0", + "bip65": "^1.0.1", + "bip68": "^1.0.3", + "bs58": "^6.0.0", + "dhttp": "^3.0.0", + "ecpair": "^3.0.0-rc.0", + "eslint": "^9.9.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.2.1", + "globals": "^15.9.0", + "hoodwink": "^2.0.0", + "minimaldata": "^1.0.2", + "mocha": "^10.6.0", + "c8": "^10.1.2", + "prettier": "^3.0.0", + "proxyquire": "^2.0.1", + "randombytes": "^2.1.0", + "regtest-client": "0.2.0", + "rimraf": "^2.6.3", + "tiny-secp256k1": "^2.2.0", + "tsx": "^4.17.0", + "typedoc": "^0.26.6", + "typescript": "^5.0.4" + }, + "license": "MIT" +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.cjs new file mode 100644 index 0000000..e2760f5 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.cjs @@ -0,0 +1,253 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.fromBase58Check = fromBase58Check; +exports.fromBech32 = fromBech32; +exports.toBase58Check = toBase58Check; +exports.toBech32 = toBech32; +exports.fromOutputScript = fromOutputScript; +exports.toOutputScript = toOutputScript; +const networks = __importStar(require('./networks.cjs')); +const payments = __importStar(require('./payments/index.cjs')); +const bscript = __importStar(require('./script.cjs')); +const types_js_1 = require('./types.cjs'); +const bech32_1 = require('bech32'); +const bs58check_1 = __importDefault(require('bs58check')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const FUTURE_SEGWIT_MAX_SIZE = 40; +const FUTURE_SEGWIT_MIN_SIZE = 2; +const FUTURE_SEGWIT_MAX_VERSION = 16; +const FUTURE_SEGWIT_MIN_VERSION = 2; +const FUTURE_SEGWIT_VERSION_DIFF = 0x50; +const FUTURE_SEGWIT_VERSION_WARNING = + 'WARNING: Sending to a future segwit version address can lead to loss of funds. ' + + 'End users MUST be warned carefully in the GUI and asked if they wish to proceed ' + + 'with caution. Wallets should verify the segwit version from the output of fromBech32, ' + + 'then decide when it is safe to use which version of segwit.'; +/** + * Converts an output buffer to a future segwit address. + * @param output - The output buffer. + * @param network - The network object. + * @returns The future segwit address. + * @throws {TypeError} If the program length or version is invalid for segwit address. + */ +function _toFutureSegwitAddress(output, network) { + const data = output.slice(2); + if ( + data.length < FUTURE_SEGWIT_MIN_SIZE || + data.length > FUTURE_SEGWIT_MAX_SIZE + ) + throw new TypeError('Invalid program length for segwit address'); + const version = output[0] - FUTURE_SEGWIT_VERSION_DIFF; + if ( + version < FUTURE_SEGWIT_MIN_VERSION || + version > FUTURE_SEGWIT_MAX_VERSION + ) + throw new TypeError('Invalid version for segwit address'); + if (output[1] !== data.length) + throw new TypeError('Invalid script for segwit address'); + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return toBech32(data, version, network.bech32); +} +/** + * Decodes a base58check encoded Bitcoin address and returns the version and hash. + * + * @param address - The base58check encoded Bitcoin address to decode. + * @returns An object containing the version and hash of the decoded address. + * @throws {TypeError} If the address is too short or too long. + */ +function fromBase58Check(address) { + const payload = bs58check_1.default.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; +} +/** + * Converts a Bech32 or Bech32m encoded address to its corresponding data representation. + * @param address - The Bech32 or Bech32m encoded address. + * @returns An object containing the version, prefix, and data of the address. + * @throws {TypeError} If the address uses the wrong encoding. + */ +function fromBech32(address) { + let result; + let version; + try { + result = bech32_1.bech32.decode(address); + } catch (e) {} + if (result) { + version = result.words[0]; + if (version !== 0) throw new TypeError(address + ' uses wrong encoding'); + } else { + result = bech32_1.bech32m.decode(address); + version = result.words[0]; + if (version === 0) throw new TypeError(address + ' uses wrong encoding'); + } + const data = bech32_1.bech32.fromWords(result.words.slice(1)); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; +} +/** + * Converts a hash to a Base58Check-encoded string. + * @param hash - The hash to be encoded. + * @param version - The version byte to be prepended to the encoded string. + * @returns The Base58Check-encoded string. + */ +function toBase58Check(hash, version) { + v.parse(v.tuple([types_js_1.Hash160bitSchema, types_js_1.UInt8Schema]), [ + hash, + version, + ]); + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, version); + payload.set(hash, 1); + return bs58check_1.default.encode(payload); +} +/** + * Converts a buffer to a Bech32 or Bech32m encoded string. + * @param data - The buffer to be encoded. + * @param version - The version number to be used in the encoding. + * @param prefix - The prefix string to be used in the encoding. + * @returns The Bech32 or Bech32m encoded string. + */ +function toBech32(data, version, prefix) { + const words = bech32_1.bech32.toWords(data); + words.unshift(version); + return version === 0 + ? bech32_1.bech32.encode(prefix, words) + : bech32_1.bech32m.encode(prefix, words); +} +/** + * Converts an output script to a Bitcoin address. + * @param output - The output script as a Buffer. + * @param network - The Bitcoin network (optional). + * @returns The Bitcoin address corresponding to the output script. + * @throws If the output script has no matching address. + */ +function fromOutputScript(output, network) { + // TODO: Network + network = network || networks.bitcoin; + try { + return payments.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wsh({ output, network }).address; + } catch (e) {} + try { + return payments.p2tr({ output, network }).address; + } catch (e) {} + try { + return _toFutureSegwitAddress(output, network); + } catch (e) {} + throw new Error(bscript.toASM(output) + ' has no matching Address'); +} +/** + * Converts a Bitcoin address to its corresponding output script. + * @param address - The Bitcoin address to convert. + * @param network - The Bitcoin network to use. Defaults to the Bitcoin network. + * @returns The corresponding output script as a Buffer. + * @throws If the address has an invalid prefix or no matching script. + */ +function toOutputScript(address, network) { + network = network || networks.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments.p2wsh({ hash: decodeBech32.data }).output; + } else if (decodeBech32.version === 1) { + if (decodeBech32.data.length === 32) + return payments.p2tr({ pubkey: decodeBech32.data }).output; + } else if ( + decodeBech32.version >= FUTURE_SEGWIT_MIN_VERSION && + decodeBech32.version <= FUTURE_SEGWIT_MAX_VERSION && + decodeBech32.data.length >= FUTURE_SEGWIT_MIN_SIZE && + decodeBech32.data.length <= FUTURE_SEGWIT_MAX_SIZE + ) { + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return bscript.compile([ + decodeBech32.version + FUTURE_SEGWIT_VERSION_DIFF, + decodeBech32.data, + ]); + } + } + } + throw new Error(address + ' has no matching Script'); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.d.ts new file mode 100644 index 0000000..06229d7 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/address.d.ts @@ -0,0 +1,72 @@ +/** + * bitcoin address decode and encode tools, include base58、bech32 and output script + * + * networks support bitcoin、bitcoin testnet and bitcoin regtest + * + * addresses support P2PKH、P2SH、P2WPKH、P2WSH、P2TR and so on + * + * @packageDocumentation + */ +import { Network } from './networks.js'; +/** base58check decode result */ +export interface Base58CheckResult { + /** address hash */ + hash: Uint8Array; + /** address version: 0x00 for P2PKH, 0x05 for P2SH */ + version: number; +} +/** bech32 decode result */ +export interface Bech32Result { + /** address version: 0x00 for P2WPKH、P2WSH, 0x01 for P2TR*/ + version: number; + /** address prefix: bc for P2WPKH、P2WSH、P2TR */ + prefix: string; + /** address data:20 bytes for P2WPKH, 32 bytes for P2WSH、P2TR */ + data: Uint8Array; +} +/** + * Decodes a base58check encoded Bitcoin address and returns the version and hash. + * + * @param address - The base58check encoded Bitcoin address to decode. + * @returns An object containing the version and hash of the decoded address. + * @throws {TypeError} If the address is too short or too long. + */ +export declare function fromBase58Check(address: string): Base58CheckResult; +/** + * Converts a Bech32 or Bech32m encoded address to its corresponding data representation. + * @param address - The Bech32 or Bech32m encoded address. + * @returns An object containing the version, prefix, and data of the address. + * @throws {TypeError} If the address uses the wrong encoding. + */ +export declare function fromBech32(address: string): Bech32Result; +/** + * Converts a hash to a Base58Check-encoded string. + * @param hash - The hash to be encoded. + * @param version - The version byte to be prepended to the encoded string. + * @returns The Base58Check-encoded string. + */ +export declare function toBase58Check(hash: Uint8Array, version: number): string; +/** + * Converts a buffer to a Bech32 or Bech32m encoded string. + * @param data - The buffer to be encoded. + * @param version - The version number to be used in the encoding. + * @param prefix - The prefix string to be used in the encoding. + * @returns The Bech32 or Bech32m encoded string. + */ +export declare function toBech32(data: Uint8Array, version: number, prefix: string): string; +/** + * Converts an output script to a Bitcoin address. + * @param output - The output script as a Buffer. + * @param network - The Bitcoin network (optional). + * @returns The Bitcoin address corresponding to the output script. + * @throws If the output script has no matching address. + */ +export declare function fromOutputScript(output: Uint8Array, network?: Network): string; +/** + * Converts a Bitcoin address to its corresponding output script. + * @param address - The Bitcoin address to convert. + * @param network - The Bitcoin network to use. Defaults to the Bitcoin network. + * @returns The corresponding output script as a Buffer. + * @throws If the address has an invalid prefix or no matching script. + */ +export declare function toOutputScript(address: string, network?: Network): Uint8Array; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.cjs new file mode 100644 index 0000000..b1d3545 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.cjs @@ -0,0 +1,115 @@ +'use strict'; +// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki +// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] +// NOTE: SIGHASH byte ignored AND restricted, truncate before use +Object.defineProperty(exports, '__esModule', { value: true }); +exports.check = check; +exports.decode = decode; +exports.encode = encode; +/** + * Checks if the given buffer is a valid BIP66-encoded signature. + * + * @param buffer - The buffer to check. + * @returns A boolean indicating whether the buffer is a valid BIP66-encoded signature. + */ +function check(buffer) { + if (buffer.length < 8) return false; + if (buffer.length > 72) return false; + if (buffer[0] !== 0x30) return false; + if (buffer[1] !== buffer.length - 2) return false; + if (buffer[2] !== 0x02) return false; + const lenR = buffer[3]; + if (lenR === 0) return false; + if (5 + lenR >= buffer.length) return false; + if (buffer[4 + lenR] !== 0x02) return false; + const lenS = buffer[5 + lenR]; + if (lenS === 0) return false; + if (6 + lenR + lenS !== buffer.length) return false; + if (buffer[4] & 0x80) return false; + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) return false; + if (buffer[lenR + 6] & 0x80) return false; + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + return false; + return true; +} +/** + * Decodes a DER-encoded signature buffer and returns the R and S values. + * @param buffer - The DER-encoded signature buffer. + * @returns An object containing the R and S values. + * @throws {Error} If the DER sequence length is too short, too long, or invalid. + * @throws {Error} If the R or S length is zero or invalid. + * @throws {Error} If the R or S value is negative or excessively padded. + */ +function decode(buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short'); + if (buffer.length > 72) throw new Error('DER sequence length is too long'); + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence'); + if (buffer[1] !== buffer.length - 2) + throw new Error('DER sequence length is invalid'); + if (buffer[2] !== 0x02) throw new Error('Expected DER integer'); + const lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero'); + if (5 + lenR >= buffer.length) throw new Error('R length is too long'); + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)'); + const lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero'); + if (6 + lenR + lenS !== buffer.length) throw new Error('S length is invalid'); + if (buffer[4] & 0x80) throw new Error('R value is negative'); + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) + throw new Error('R value excessively padded'); + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative'); + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + throw new Error('S value excessively padded'); + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR), + }; +} +/* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ +function encode(r, s) { + const lenR = r.length; + const lenS = s.length; + if (lenR === 0) throw new Error('R length is zero'); + if (lenS === 0) throw new Error('S length is zero'); + if (lenR > 33) throw new Error('R length is too long'); + if (lenS > 33) throw new Error('S length is too long'); + if (r[0] & 0x80) throw new Error('R value is negative'); + if (s[0] & 0x80) throw new Error('S value is negative'); + if (lenR > 1 && r[0] === 0x00 && !(r[1] & 0x80)) + throw new Error('R value excessively padded'); + if (lenS > 1 && s[0] === 0x00 && !(s[1] & 0x80)) + throw new Error('S value excessively padded'); + const signature = new Uint8Array(6 + lenR + lenS); + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + signature.set(r, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + signature.set(s, 6 + lenR); + return signature; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.d.ts new file mode 100644 index 0000000..b7372e6 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bip66.d.ts @@ -0,0 +1,20 @@ +/** + * Checks if the given buffer is a valid BIP66-encoded signature. + * + * @param buffer - The buffer to check. + * @returns A boolean indicating whether the buffer is a valid BIP66-encoded signature. + */ +export declare function check(buffer: Uint8Array): boolean; +/** + * Decodes a DER-encoded signature buffer and returns the R and S values. + * @param buffer - The DER-encoded signature buffer. + * @returns An object containing the R and S values. + * @throws {Error} If the DER sequence length is too short, too long, or invalid. + * @throws {Error} If the R or S length is zero or invalid. + * @throws {Error} If the R or S value is negative or excessively padded. + */ +export declare function decode(buffer: Uint8Array): { + r: Uint8Array; + s: Uint8Array; +}; +export declare function encode(r: Uint8Array, s: Uint8Array): Uint8Array; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.cjs new file mode 100644 index 0000000..bc4db55 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.cjs @@ -0,0 +1,268 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Block = void 0; +const bufferutils_js_1 = require('./bufferutils.cjs'); +const bcrypto = __importStar(require('./crypto.cjs')); +const merkle_js_1 = require('./merkle.cjs'); +const transaction_js_1 = require('./transaction.cjs'); +const v = __importStar(require('valibot')); +const tools = __importStar(require('uint8array-tools')); +const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', +); +const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', +); +class Block { + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_js_1.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_js_1.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(tools.fromHex(hex)); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = new Uint8Array(32); + target[29 - exponent] = (mantissa >> 16) & 0xff; + target[30 - exponent] = (mantissa >> 8) & 0xff; + target[31 - exponent] = mantissa & 0xff; + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + v.parse(v.array(v.object({ getHash: v.function() })), transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = (0, merkle_js_1.fastMerkleRoot)(hashes, bcrypto.hash256); + return forWitness + ? bcrypto.hash256( + tools.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + version = 1; + prevHash = undefined; + merkleRoot = undefined; + timestamp = 0; + witnessCommit = undefined; + bits = 0; + nonce = 0; + transactions = undefined; + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter( + out => + tools.compare( + out.script.slice(0, 6), + Uint8Array.from([0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed]), + ) === 0, + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Uint8Array && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Uint8Array && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + bufferutils_js_1.varuint.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto.hash256(this.toBuffer(true)); + } + getId() { + return tools.toHex((0, bufferutils_js_1.reverseBuffer)(this.getHash())); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = new Uint8Array(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_js_1.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + const { bytes } = bufferutils_js_1.varuint.encode( + this.transactions.length, + buffer, + bufferWriter.offset, + ); + bufferWriter.offset += bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return tools.toHex(this.toBuffer(headersOnly)); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = (0, bufferutils_js_1.reverseBuffer)(this.getHash()); + const target = Block.calculateTarget(this.bits); + return tools.compare(hash, target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return tools.compare(this.merkleRoot, actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return tools.compare(this.witnessCommit, actualWitnessCommit) === 0; + } +} +exports.Block = Block; +function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); +} +function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.d.ts new file mode 100644 index 0000000..8afce27 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/block.d.ts @@ -0,0 +1,29 @@ +import { Transaction } from './transaction.js'; +export declare class Block { + static fromBuffer(buffer: Uint8Array): Block; + static fromHex(hex: string): Block; + static calculateTarget(bits: number): Uint8Array; + static calculateMerkleRoot(transactions: Transaction[], forWitness?: boolean): Uint8Array; + version: number; + prevHash?: Uint8Array; + merkleRoot?: Uint8Array; + timestamp: number; + witnessCommit?: Uint8Array; + bits: number; + nonce: number; + transactions?: Transaction[]; + getWitnessCommit(): Uint8Array | null; + hasWitnessCommit(): boolean; + hasWitness(): boolean; + weight(): number; + byteLength(headersOnly?: boolean, allowWitness?: boolean): number; + getHash(): Uint8Array; + getId(): string; + getUTCDate(): Date; + toBuffer(headersOnly?: boolean): Uint8Array; + toHex(headersOnly?: boolean): string; + checkTxRoots(): boolean; + checkProofOfWork(): boolean; + private __checkMerkleRoot; + private __checkWitnessCommit; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.cjs new file mode 100644 index 0000000..c524532 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.cjs @@ -0,0 +1,207 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.BufferReader = exports.BufferWriter = exports.varuint = void 0; +exports.reverseBuffer = reverseBuffer; +exports.cloneBuffer = cloneBuffer; +const types = __importStar(require('./types.cjs')); +const varuint = __importStar(require('varuint-bitcoin')); +exports.varuint = varuint; +const v = __importStar(require('valibot')); +const tools = __importStar(require('uint8array-tools')); +const MAX_JS_NUMBER = 0x001fffffffffffff; +// https://github.com/feross/buffer/blob/master/index.js#L1127 +function verifuint(value, max) { + if (typeof value !== 'number' && typeof value !== 'bigint') + throw new Error('cannot write a non-number as a number'); + if (value < 0 && value < BigInt(0)) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max && value > BigInt(max)) + throw new Error('RangeError: value out of range'); + if (Math.floor(Number(value)) !== Number(value)) + throw new Error('value has a fractional component'); +} +/** + * Reverses the order of bytes in a buffer. + * @param buffer - The buffer to reverse. + * @returns A new buffer with the bytes reversed. + */ +function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +function cloneBuffer(buffer) { + const clone = new Uint8Array(buffer.length); + clone.set(buffer); + return clone; +} +/** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ +class BufferWriter { + buffer; + offset; + static withCapacity(size) { + return new BufferWriter(new Uint8Array(size)); + } + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + v.parse(v.tuple([types.BufferSchema, types.UInt32Schema]), [ + buffer, + offset, + ]); + } + writeUInt8(i) { + this.offset = tools.writeUInt8(this.buffer, this.offset, i); + } + writeInt32(i) { + this.offset = tools.writeInt32(this.buffer, this.offset, i, 'LE'); + } + writeInt64(i) { + this.offset = tools.writeInt64(this.buffer, this.offset, BigInt(i), 'LE'); + } + writeUInt32(i) { + this.offset = tools.writeUInt32(this.buffer, this.offset, i, 'LE'); + } + writeUInt64(i) { + this.offset = tools.writeUInt64(this.buffer, this.offset, BigInt(i), 'LE'); + } + writeVarInt(i) { + const { bytes } = varuint.encode(i, this.buffer, this.offset); + this.offset += bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.buffer.set(slice, this.offset); + this.offset += slice.length; + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + end() { + if (this.buffer.length === this.offset) { + return this.buffer; + } + throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`); + } +} +exports.BufferWriter = BufferWriter; +/** + * Helper class for reading of bitcoin data types from a buffer. + */ +class BufferReader { + buffer; + offset; + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + v.parse(v.tuple([types.BufferSchema, types.UInt32Schema]), [ + buffer, + offset, + ]); + } + readUInt8() { + const result = tools.readUInt8(this.buffer, this.offset); + this.offset++; + return result; + } + readInt32() { + const result = tools.readInt32(this.buffer, this.offset, 'LE'); + this.offset += 4; + return result; + } + readUInt32() { + const result = tools.readUInt32(this.buffer, this.offset, 'LE'); + this.offset += 4; + return result; + } + readInt64() { + const result = tools.readInt64(this.buffer, this.offset, 'LE'); + this.offset += 8; + return result; + } + readVarInt() { + const { bigintValue, bytes } = varuint.decode(this.buffer, this.offset); + this.offset += bytes; + return bigintValue; + } + readSlice(n) { + verifuint(n, MAX_JS_NUMBER); + const num = Number(n); + if (this.buffer.length < this.offset + num) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + num); + this.offset += num; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } +} +exports.BufferReader = BufferReader; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.d.ts new file mode 100644 index 0000000..0998bfa --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/bufferutils.d.ts @@ -0,0 +1,44 @@ +import * as varuint from 'varuint-bitcoin'; +export { varuint }; +/** + * Reverses the order of bytes in a buffer. + * @param buffer - The buffer to reverse. + * @returns A new buffer with the bytes reversed. + */ +export declare function reverseBuffer(buffer: Uint8Array): Uint8Array; +export declare function cloneBuffer(buffer: Uint8Array): Uint8Array; +/** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ +export declare class BufferWriter { + buffer: Uint8Array; + offset: number; + static withCapacity(size: number): BufferWriter; + constructor(buffer: Uint8Array, offset?: number); + writeUInt8(i: number): void; + writeInt32(i: number): void; + writeInt64(i: number | bigint): void; + writeUInt32(i: number): void; + writeUInt64(i: number | bigint): void; + writeVarInt(i: number): void; + writeSlice(slice: Uint8Array): void; + writeVarSlice(slice: Uint8Array): void; + writeVector(vector: Uint8Array[]): void; + end(): Uint8Array; +} +/** + * Helper class for reading of bitcoin data types from a buffer. + */ +export declare class BufferReader { + buffer: Uint8Array; + offset: number; + constructor(buffer: Uint8Array, offset?: number); + readUInt8(): number; + readInt32(): number; + readUInt32(): number; + readInt64(): bigint; + readVarInt(): bigint; + readSlice(n: number | bigint): Uint8Array; + readVarSlice(): Uint8Array; + readVector(): Uint8Array[]; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.cjs new file mode 100644 index 0000000..54d5771 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.cjs @@ -0,0 +1,141 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.TAGGED_HASH_PREFIXES = exports.TAGS = void 0; +exports.hash160 = hash160; +exports.hash256 = hash256; +exports.taggedHash = taggedHash; +/** + * A module for hashing functions. + * include ripemd160、sha1、sha256、hash160、hash256、taggedHash + * + * @packageDocumentation + */ +const ripemd160_1 = require('@noble/hashes/ripemd160'); +const sha256_1 = require('@noble/hashes/sha256'); +const tools = __importStar(require('uint8array-tools')); +function hash160(buffer) { + return (0, ripemd160_1.ripemd160)((0, sha256_1.sha256)(buffer)); +} +function hash256(buffer) { + return (0, sha256_1.sha256)((0, sha256_1.sha256)(buffer)); +} +exports.TAGS = [ + 'BIP0340/challenge', + 'BIP0340/aux', + 'BIP0340/nonce', + 'TapLeaf', + 'TapBranch', + 'TapSighash', + 'TapTweak', + 'KeyAgg list', + 'KeyAgg coefficient', +]; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +/** + * Defines the tagged hash prefixes used in the crypto module. + */ +exports.TAGGED_HASH_PREFIXES = { + 'BIP0340/challenge': Uint8Array.from([ + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + ]), + 'BIP0340/aux': Uint8Array.from([ + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + ]), + 'BIP0340/nonce': Uint8Array.from([ + 7, 73, 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, + 52, 215, 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, 7, 73, + 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, 52, 215, + 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, + ]), + TapLeaf: Uint8Array.from([ + 174, 234, 143, 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, + 95, 28, 181, 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, 174, 234, 143, + 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, 95, 28, 181, + 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, + ]), + TapBranch: Uint8Array.from([ + 25, 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, + 33, 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, 25, + 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, 33, + 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, + ]), + TapSighash: Uint8Array.from([ + 244, 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, + 149, 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, 244, + 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, 149, + 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, + ]), + TapTweak: Uint8Array.from([ + 232, 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, + 156, 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, 232, + 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, 156, + 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, + ]), + 'KeyAgg list': Uint8Array.from([ + 72, 28, 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, + 215, 49, 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, 72, 28, + 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, 215, 49, + 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, + ]), + 'KeyAgg coefficient': Uint8Array.from([ + 191, 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, + 130, 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, 191, + 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, 130, + 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, + ]), +}; +function taggedHash(prefix, data) { + return (0, sha256_1.sha256)( + tools.concat([exports.TAGGED_HASH_PREFIXES[prefix], data]), + ); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.d.ts new file mode 100644 index 0000000..5429162 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/crypto.d.ts @@ -0,0 +1,14 @@ +export declare function hash160(buffer: Uint8Array): Uint8Array; +export declare function hash256(buffer: Uint8Array): Uint8Array; +export declare const TAGS: readonly ["BIP0340/challenge", "BIP0340/aux", "BIP0340/nonce", "TapLeaf", "TapBranch", "TapSighash", "TapTweak", "KeyAgg list", "KeyAgg coefficient"]; +export type TaggedHashPrefix = (typeof TAGS)[number]; +type TaggedHashPrefixes = { + [key in TaggedHashPrefix]: Uint8Array; +}; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +/** + * Defines the tagged hash prefixes used in the crypto module. + */ +export declare const TAGGED_HASH_PREFIXES: TaggedHashPrefixes; +export declare function taggedHash(prefix: TaggedHashPrefix, data: Uint8Array): Uint8Array; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.cjs new file mode 100644 index 0000000..9b6dc7f --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.cjs @@ -0,0 +1,154 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.initEccLib = initEccLib; +exports.getEccLib = getEccLib; +const tools = __importStar(require('uint8array-tools')); +const _ECCLIB_CACHE = {}; +/** + * Initializes the ECC library with the provided instance. + * If `eccLib` is `undefined`, the library will be cleared. + * If `eccLib` is a new instance, it will be verified before setting it as the active library. + * + * @param eccLib The instance of the ECC library to initialize. + */ +function initEccLib(eccLib) { + if (!eccLib) { + // allow clearing the library + _ECCLIB_CACHE.eccLib = eccLib; + } else if (eccLib !== _ECCLIB_CACHE.eccLib) { + // new instance, verify it + verifyEcc(eccLib); + _ECCLIB_CACHE.eccLib = eccLib; + } +} +/** + * Retrieves the ECC Library instance. + * Throws an error if the ECC Library is not provided. + * You must call initEccLib() with a valid TinySecp256k1Interface instance before calling this function. + * @returns The ECC Library instance. + * @throws Error if the ECC Library is not provided. + */ +function getEccLib() { + if (!_ECCLIB_CACHE.eccLib) + throw new Error( + 'No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance', + ); + return _ECCLIB_CACHE.eccLib; +} +const h = hex => tools.fromHex(hex); +/** + * Verifies the ECC functionality. + * + * @param ecc - The TinySecp256k1Interface object. + */ +function verifyEcc(ecc) { + assert(typeof ecc.isXOnlyPoint === 'function'); + assert( + ecc.isXOnlyPoint( + h('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000001'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000000'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + ), + ); + assert(typeof ecc.xOnlyPointAddTweak === 'function'); + tweakAddVectors.forEach(t => { + const r = ecc.xOnlyPointAddTweak(h(t.pubkey), h(t.tweak)); + if (t.result === null) { + assert(r === null); + } else { + assert(r !== null); + assert(r.parity === t.parity); + assert(tools.compare(r.xOnlyPubkey, h(t.result)) === 0); + } + }); +} +function assert(bool) { + if (!bool) throw new Error('ecc library invalid'); +} +const tweakAddVectors = [ + { + pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + tweak: 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + parity: -1, + result: null, + }, + { + pubkey: '1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b', + tweak: 'a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac', + parity: 1, + result: 'e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf', + }, + { + pubkey: '2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991', + tweak: '823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47', + parity: 0, + result: '9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c', + }, +]; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.d.ts new file mode 100644 index 0000000..108f6cc --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ecc_lib.d.ts @@ -0,0 +1,17 @@ +import { TinySecp256k1Interface } from './types.js'; +/** + * Initializes the ECC library with the provided instance. + * If `eccLib` is `undefined`, the library will be cleared. + * If `eccLib` is a new instance, it will be verified before setting it as the active library. + * + * @param eccLib The instance of the ECC library to initialize. + */ +export declare function initEccLib(eccLib: TinySecp256k1Interface | undefined): void; +/** + * Retrieves the ECC Library instance. + * Throws an error if the ECC Library is not provided. + * You must call initEccLib() with a valid TinySecp256k1Interface instance before calling this function. + * @returns The ECC Library instance. + * @throws Error if the ECC Library is not provided. + */ +export declare function getEccLib(): TinySecp256k1Interface; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.cjs new file mode 100644 index 0000000..3003335 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.cjs @@ -0,0 +1,103 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.initEccLib = + exports.Transaction = + exports.opcodes = + exports.Psbt = + exports.Block = + exports.script = + exports.payments = + exports.networks = + exports.crypto = + exports.address = + void 0; +const address = __importStar(require('./address.cjs')); +exports.address = address; +const crypto = __importStar(require('./crypto.cjs')); +exports.crypto = crypto; +const networks = __importStar(require('./networks.cjs')); +exports.networks = networks; +const payments = __importStar(require('./payments/index.cjs')); +exports.payments = payments; +const script = __importStar(require('./script.cjs')); +exports.script = script; +var block_js_1 = require('./block.cjs'); +Object.defineProperty(exports, 'Block', { + enumerable: true, + get: function () { + return block_js_1.Block; + }, +}); +var psbt_js_1 = require('./psbt.cjs'); +Object.defineProperty(exports, 'Psbt', { + enumerable: true, + get: function () { + return psbt_js_1.Psbt; + }, +}); +/** @hidden */ +var ops_js_1 = require('./ops.cjs'); +Object.defineProperty(exports, 'opcodes', { + enumerable: true, + get: function () { + return ops_js_1.OPS; + }, +}); +var transaction_js_1 = require('./transaction.cjs'); +Object.defineProperty(exports, 'Transaction', { + enumerable: true, + get: function () { + return transaction_js_1.Transaction; + }, +}); +var ecc_lib_js_1 = require('./ecc_lib.cjs'); +Object.defineProperty(exports, 'initEccLib', { + enumerable: true, + get: function () { + return ecc_lib_js_1.initEccLib; + }, +}); diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.d.ts new file mode 100644 index 0000000..dc4335d --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/index.d.ts @@ -0,0 +1,19 @@ +import * as address from './address.js'; +import * as crypto from './crypto.js'; +import * as networks from './networks.js'; +import * as payments from './payments/index.js'; +import * as script from './script.js'; +export { address, crypto, networks, payments, script }; +export { Block } from './block.js'; +/** @hidden */ +export { TaggedHashPrefix } from './crypto.js'; +export { Psbt, PsbtTxInput, PsbtTxOutput, Signer, SignerAsync, HDSigner, HDSignerAsync, } from './psbt.js'; +/** @hidden */ +export { OPS as opcodes } from './ops.js'; +export { Transaction } from './transaction.js'; +/** @hidden */ +export { Network } from './networks.js'; +/** @hidden */ +export { Payment, PaymentCreator, PaymentOpts, Stack, StackElement, } from './payments/index.js'; +export { Input as TxInput, Output as TxOutput } from './transaction.js'; +export { initEccLib } from './ecc_lib.js'; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.cjs new file mode 100644 index 0000000..a94e972 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.cjs @@ -0,0 +1,74 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.fastMerkleRoot = fastMerkleRoot; +const tools = __importStar(require('uint8array-tools')); +/** + * Calculates the Merkle root of an array of buffers using a specified digest function. + * + * @param values - The array of buffers. + * @param digestFn - The digest function used to calculate the hash of the concatenated buffers. + * @returns The Merkle root as a buffer. + * @throws {TypeError} If the values parameter is not an array or the digestFn parameter is not a function. + */ +function fastMerkleRoot(values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array'); + if (typeof digestFn !== 'function') + throw TypeError('Expected digest Function'); + let length = values.length; + const results = values.concat(); + while (length > 1) { + let j = 0; + for (let i = 0; i < length; i += 2, ++j) { + const left = results[i]; + const right = i + 1 === length ? left : results[i + 1]; + const data = tools.concat([left, right]); + results[j] = digestFn(data); + } + length = j; + } + return results[0]; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.d.ts new file mode 100644 index 0000000..b98fe06 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/merkle.d.ts @@ -0,0 +1,9 @@ +/** + * Calculates the Merkle root of an array of buffers using a specified digest function. + * + * @param values - The array of buffers. + * @param digestFn - The digest function used to calculate the hash of the concatenated buffers. + * @returns The Merkle root as a buffer. + * @throws {TypeError} If the values parameter is not an array or the digestFn parameter is not a function. + */ +export declare function fastMerkleRoot(values: Uint8Array[], digestFn: (b: Uint8Array) => Uint8Array): Uint8Array; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.cjs new file mode 100644 index 0000000..75cdf30 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.cjs @@ -0,0 +1,71 @@ +'use strict'; +// https://en.bitcoin.it/wiki/List_of_address_prefixes +// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 +Object.defineProperty(exports, '__esModule', { value: true }); +exports.testnet = exports.regtest = exports.bitcoin = void 0; +/** + * Represents the Bitcoin network configuration. + */ +exports.bitcoin = { + /** + * The message prefix used for signing Bitcoin messages. + */ + messagePrefix: '\x18Bitcoin Signed Message:\n', + /** + * The Bech32 prefix used for Bitcoin addresses. + */ + bech32: 'bc', + /** + * The BIP32 key prefixes for Bitcoin. + */ + bip32: { + /** + * The public key prefix for BIP32 extended public keys. + */ + public: 0x0488b21e, + /** + * The private key prefix for BIP32 extended private keys. + */ + private: 0x0488ade4, + }, + /** + * The prefix for Bitcoin public key hashes. + */ + pubKeyHash: 0x00, + /** + * The prefix for Bitcoin script hashes. + */ + scriptHash: 0x05, + /** + * The prefix for Bitcoin Wallet Import Format (WIF) private keys. + */ + wif: 0x80, +}; +/** + * Represents the regtest network configuration. + */ +exports.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; +/** + * Represents the testnet network configuration. + */ +exports.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.d.ts new file mode 100644 index 0000000..f9b020d --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/networks.d.ts @@ -0,0 +1,30 @@ +/** + * Represents a Bitcoin network configuration,including messagePrefix, bech32, bip32, pubKeyHash, scriptHash, wif. + * Support bitcoin、bitcoin testnet and bitcoin regtest. + * @packageDocumentation + */ +export interface Network { + messagePrefix: string; + bech32: string; + bip32: Bip32; + pubKeyHash: number; + scriptHash: number; + wif: number; +} +interface Bip32 { + public: number; + private: number; +} +/** + * Represents the Bitcoin network configuration. + */ +export declare const bitcoin: Network; +/** + * Represents the regtest network configuration. + */ +export declare const regtest: Network; +/** + * Represents the testnet network configuration. + */ +export declare const testnet: Network; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.cjs new file mode 100644 index 0000000..7853ad0 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.cjs @@ -0,0 +1,131 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.REVERSE_OPS = exports.OPS = void 0; +const OPS = { + OP_FALSE: 0, + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_RESERVED: 80, + OP_TRUE: 81, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + OP_NOP: 97, + OP_VER: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_VERIF: 101, + OP_VERNOTIF: 102, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + OP_CAT: 126, + OP_SUBSTR: 127, + OP_LEFT: 128, + OP_RIGHT: 129, + OP_SIZE: 130, + OP_INVERT: 131, + OP_AND: 132, + OP_OR: 133, + OP_XOR: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_RESERVED1: 137, + OP_RESERVED2: 138, + OP_1ADD: 139, + OP_1SUB: 140, + OP_2MUL: 141, + OP_2DIV: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + OP_ADD: 147, + OP_SUB: 148, + OP_MUL: 149, + OP_DIV: 150, + OP_MOD: 151, + OP_LSHIFT: 152, + OP_RSHIFT: 153, + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + OP_WITHIN: 165, + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + OP_NOP1: 176, + OP_NOP2: 177, + OP_CHECKLOCKTIMEVERIFY: 177, + OP_NOP3: 178, + OP_CHECKSEQUENCEVERIFY: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + OP_CHECKSIGADD: 186, + OP_PUBKEYHASH: 253, + OP_PUBKEY: 254, + OP_INVALIDOPCODE: 255, +}; +exports.OPS = OPS; +const REVERSE_OPS = {}; +exports.REVERSE_OPS = REVERSE_OPS; +for (const op of Object.keys(OPS)) { + const code = OPS[op]; + REVERSE_OPS[code] = op; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.d.ts new file mode 100644 index 0000000..cda7a84 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/ops.d.ts @@ -0,0 +1,7 @@ +declare const OPS: { + [key: string]: number; +}; +declare const REVERSE_OPS: { + [key: number]: string; +}; +export { OPS, REVERSE_OPS }; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.cjs new file mode 100644 index 0000000..c2adb34 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.cjs @@ -0,0 +1,192 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.MAX_TAPTREE_DEPTH = exports.LEAF_VERSION_TAPSCRIPT = void 0; +exports.rootHashFromPath = rootHashFromPath; +exports.toHashTree = toHashTree; +exports.findScriptPath = findScriptPath; +exports.tapleafHash = tapleafHash; +exports.tapTweakHash = tapTweakHash; +exports.tweakKey = tweakKey; +const ecc_lib_js_1 = require('../ecc_lib.cjs'); +const bcrypto = __importStar(require('../crypto.cjs')); +const bufferutils_js_1 = require('../bufferutils.cjs'); +const types_js_1 = require('../types.cjs'); +const tools = __importStar(require('uint8array-tools')); +exports.LEAF_VERSION_TAPSCRIPT = 0xc0; +exports.MAX_TAPTREE_DEPTH = 128; +const isHashBranch = ht => 'left' in ht && 'right' in ht; +/** + * Calculates the root hash from a given control block and leaf hash. + * @param controlBlock - The control block buffer. + * @param leafHash - The leaf hash buffer. + * @returns The root hash buffer. + * @throws {TypeError} If the control block length is less than 33. + */ +function rootHashFromPath(controlBlock, leafHash) { + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + const m = (controlBlock.length - 33) / 32; + let kj = leafHash; + for (let j = 0; j < m; j++) { + const ej = controlBlock.slice(33 + 32 * j, 65 + 32 * j); + if (tools.compare(kj, ej) < 0) { + kj = tapBranchHash(kj, ej); + } else { + kj = tapBranchHash(ej, kj); + } + } + return kj; +} +/** + * Build a hash tree of merkle nodes from the scripts binary tree. + * @param scriptTree - the tree of scripts to pairwise hash. + */ +function toHashTree(scriptTree) { + if ((0, types_js_1.isTapleaf)(scriptTree)) + return { hash: tapleafHash(scriptTree) }; + const hashes = [toHashTree(scriptTree[0]), toHashTree(scriptTree[1])]; + // hashes.sort((a, b) => a.hash.compare(b.hash)); + hashes.sort((a, b) => tools.compare(a.hash, b.hash)); + const [left, right] = hashes; + return { + hash: tapBranchHash(left.hash, right.hash), + left, + right, + }; +} +/** + * Given a HashTree, finds the path from a particular hash to the root. + * @param node - the root of the tree + * @param hash - the hash to search for + * @returns - array of sibling hashes, from leaf (inclusive) to root + * (exclusive) needed to prove inclusion of the specified hash. undefined if no + * path is found + */ +function findScriptPath(node, hash) { + if (isHashBranch(node)) { + const leftPath = findScriptPath(node.left, hash); + if (leftPath !== undefined) return [...leftPath, node.right.hash]; + const rightPath = findScriptPath(node.right, hash); + if (rightPath !== undefined) return [...rightPath, node.left.hash]; + } else if (tools.compare(node.hash, hash) === 0) { + return []; + } + return undefined; +} +/** + * Calculates the tapleaf hash for a given Tapleaf object. + * @param leaf - The Tapleaf object to calculate the hash for. + * @returns The tapleaf hash as a Buffer. + */ +function tapleafHash(leaf) { + const version = leaf.version || exports.LEAF_VERSION_TAPSCRIPT; + return bcrypto.taggedHash( + 'TapLeaf', + tools.concat([Uint8Array.from([version]), serializeScript(leaf.output)]), + ); +} +/** + * Computes the taproot tweak hash for a given public key and optional hash. + * If a hash is provided, the public key and hash are concatenated before computing the hash. + * If no hash is provided, only the public key is used to compute the hash. + * + * @param pubKey - The public key buffer. + * @param h - The optional hash buffer. + * @returns The taproot tweak hash. + */ +function tapTweakHash(pubKey, h) { + return bcrypto.taggedHash( + 'TapTweak', + tools.concat(h ? [pubKey, h] : [pubKey]), + ); +} +/** + * Tweak a public key with a given tweak hash. + * @param pubKey - The public key to be tweaked. + * @param h - The tweak hash. + * @returns The tweaked public key or null if the input is invalid. + */ +function tweakKey(pubKey, h) { + if (!(pubKey instanceof Uint8Array)) return null; + if (pubKey.length !== 32) return null; + if (h && h.length !== 32) return null; + const tweakHash = tapTweakHash(pubKey, h); + const res = (0, ecc_lib_js_1.getEccLib)().xOnlyPointAddTweak( + pubKey, + tweakHash, + ); + if (!res || res.xOnlyPubkey === null) return null; + return { + parity: res.parity, + x: Uint8Array.from(res.xOnlyPubkey), + }; +} +/** + * Computes the TapBranch hash by concatenating two buffers and applying the 'TapBranch' tagged hash algorithm. + * + * @param a - The first buffer. + * @param b - The second buffer. + * @returns The TapBranch hash of the concatenated buffers. + */ +function tapBranchHash(a, b) { + return bcrypto.taggedHash('TapBranch', tools.concat([a, b])); +} +/** + * Serializes a script by encoding its length as a varint and concatenating it with the script. + * + * @param s - The script to be serialized. + * @returns The serialized script as a Buffer. + */ +function serializeScript(s) { + /* global BigInt */ + const varintLen = bufferutils_js_1.varuint.encodingLength(s.length); + const buffer = new Uint8Array(varintLen); + bufferutils_js_1.varuint.encode(s.length, buffer); + return tools.concat([buffer, s]); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.d.ts new file mode 100644 index 0000000..12b3885 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/bip341.d.ts @@ -0,0 +1,68 @@ +import { Tapleaf, Taptree } from '../types.js'; +export declare const LEAF_VERSION_TAPSCRIPT = 192; +export declare const MAX_TAPTREE_DEPTH = 128; +interface HashLeaf { + hash: Uint8Array; +} +interface HashBranch { + hash: Uint8Array; + left: HashTree; + right: HashTree; +} +interface TweakedPublicKey { + parity: number; + x: Uint8Array; +} +/** + * Binary tree representing leaf, branch, and root node hashes of a Taptree. + * Each node contains a hash, and potentially left and right branch hashes. + * This tree is used for 2 purposes: Providing the root hash for tweaking, + * and calculating merkle inclusion proofs when constructing a control block. + */ +export type HashTree = HashLeaf | HashBranch; +/** + * Calculates the root hash from a given control block and leaf hash. + * @param controlBlock - The control block buffer. + * @param leafHash - The leaf hash buffer. + * @returns The root hash buffer. + * @throws {TypeError} If the control block length is less than 33. + */ +export declare function rootHashFromPath(controlBlock: Uint8Array, leafHash: Uint8Array): Uint8Array; +/** + * Build a hash tree of merkle nodes from the scripts binary tree. + * @param scriptTree - the tree of scripts to pairwise hash. + */ +export declare function toHashTree(scriptTree: Taptree): HashTree; +/** + * Given a HashTree, finds the path from a particular hash to the root. + * @param node - the root of the tree + * @param hash - the hash to search for + * @returns - array of sibling hashes, from leaf (inclusive) to root + * (exclusive) needed to prove inclusion of the specified hash. undefined if no + * path is found + */ +export declare function findScriptPath(node: HashTree, hash: Uint8Array): Uint8Array[] | undefined; +/** + * Calculates the tapleaf hash for a given Tapleaf object. + * @param leaf - The Tapleaf object to calculate the hash for. + * @returns The tapleaf hash as a Buffer. + */ +export declare function tapleafHash(leaf: Tapleaf): Uint8Array; +/** + * Computes the taproot tweak hash for a given public key and optional hash. + * If a hash is provided, the public key and hash are concatenated before computing the hash. + * If no hash is provided, only the public key is used to compute the hash. + * + * @param pubKey - The public key buffer. + * @param h - The optional hash buffer. + * @returns The taproot tweak hash. + */ +export declare function tapTweakHash(pubKey: Uint8Array, h: Uint8Array | undefined): Uint8Array; +/** + * Tweak a public key with a given tweak hash. + * @param pubKey - The public key to be tweaked. + * @param h - The tweak hash. + * @returns The tweaked public key or null if the input is invalid. + */ +export declare function tweakKey(pubKey: Uint8Array, h: Uint8Array | undefined): TweakedPublicKey | null; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.cjs new file mode 100644 index 0000000..42034a9 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.cjs @@ -0,0 +1,97 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2data = p2data; +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +// output: OP_RETURN ... +/** + * Embeds data in a Bitcoin payment. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The modified payment object. + * @throws {TypeError} If there is not enough data or if the output is invalid. + */ +function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + output: types_js_1.BufferSchema, + data: v.array(types_js_1.BufferSchema), + }), + ), + a, + ); + const network = a.network || networks_js_1.bitcoin; + const o = { name: 'embed', network }; + lazy.prop(o, 'output', () => { + if (!a.data) return; + return bscript.compile([OPS.OP_RETURN].concat(a.data)); + }); + lazy.prop(o, 'data', () => { + if (!a.output) return; + return bscript.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript.decompile(a.output); + if (chunks[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(chunk => v.is(types_js_1.BufferSchema, chunk))) + throw new TypeError('Output is invalid'); + if (a.data && !(0, types_js_1.stacksEqual)(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.d.ts new file mode 100644 index 0000000..790c13d --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/embed.d.ts @@ -0,0 +1,9 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Embeds data in a Bitcoin payment. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The modified payment object. + * @throws {TypeError} If there is not enough data or if the output is invalid. + */ +export declare function p2data(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.cjs new file mode 100644 index 0000000..2db18ed --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.cjs @@ -0,0 +1,69 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2tr = + exports.p2wsh = + exports.p2wpkh = + exports.p2sh = + exports.p2pkh = + exports.p2pk = + exports.p2ms = + exports.embed = + void 0; +const embed_js_1 = require('./embed.cjs'); +Object.defineProperty(exports, 'embed', { + enumerable: true, + get: function () { + return embed_js_1.p2data; + }, +}); +const p2ms_js_1 = require('./p2ms.cjs'); +Object.defineProperty(exports, 'p2ms', { + enumerable: true, + get: function () { + return p2ms_js_1.p2ms; + }, +}); +const p2pk_js_1 = require('./p2pk.cjs'); +Object.defineProperty(exports, 'p2pk', { + enumerable: true, + get: function () { + return p2pk_js_1.p2pk; + }, +}); +const p2pkh_js_1 = require('./p2pkh.cjs'); +Object.defineProperty(exports, 'p2pkh', { + enumerable: true, + get: function () { + return p2pkh_js_1.p2pkh; + }, +}); +const p2sh_js_1 = require('./p2sh.cjs'); +Object.defineProperty(exports, 'p2sh', { + enumerable: true, + get: function () { + return p2sh_js_1.p2sh; + }, +}); +const p2wpkh_js_1 = require('./p2wpkh.cjs'); +Object.defineProperty(exports, 'p2wpkh', { + enumerable: true, + get: function () { + return p2wpkh_js_1.p2wpkh; + }, +}); +const p2wsh_js_1 = require('./p2wsh.cjs'); +Object.defineProperty(exports, 'p2wsh', { + enumerable: true, + get: function () { + return p2wsh_js_1.p2wsh; + }, +}); +const p2tr_js_1 = require('./p2tr.cjs'); +Object.defineProperty(exports, 'p2tr', { + enumerable: true, + get: function () { + return p2tr_js_1.p2tr; + }, +}); +// TODO +// witness commitment diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.d.ts new file mode 100644 index 0000000..ce4b424 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/index.d.ts @@ -0,0 +1,47 @@ +/** + * Represents a payment object, which is used to create a payment. + * + * Supports P2PKH、P2SH、P2WPKH、P2WSH、P2TR and so on + * + * @packageDocumentation + */ +import { Network } from '../networks.js'; +import { Taptree } from '../types.js'; +import { p2data as embed } from './embed.js'; +import { p2ms } from './p2ms.js'; +import { p2pk } from './p2pk.js'; +import { p2pkh } from './p2pkh.js'; +import { p2sh } from './p2sh.js'; +import { p2wpkh } from './p2wpkh.js'; +import { p2wsh } from './p2wsh.js'; +import { p2tr } from './p2tr.js'; +export interface Payment { + name?: string; + network?: Network; + output?: Uint8Array; + data?: Uint8Array[]; + m?: number; + n?: number; + pubkeys?: Uint8Array[]; + input?: Uint8Array; + signatures?: Uint8Array[]; + internalPubkey?: Uint8Array; + pubkey?: Uint8Array; + signature?: Uint8Array; + address?: string; + hash?: Uint8Array; + redeem?: Payment; + redeemVersion?: number; + scriptTree?: Taptree; + witness?: Uint8Array[]; +} +export type PaymentCreator = (a: Payment, opts?: PaymentOpts) => Payment; +export type PaymentFunction = () => Payment; +export interface PaymentOpts { + validate?: boolean; + allowIncomplete?: boolean; +} +export type StackElement = Uint8Array | number; +export type Stack = StackElement[]; +export type StackFunction = () => Stack; +export { embed, p2ms, p2pk, p2pkh, p2sh, p2wpkh, p2wsh, p2tr }; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.cjs new file mode 100644 index 0000000..489d459 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.cjs @@ -0,0 +1,31 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.prop = prop; +exports.value = value; +function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); +} +function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.d.ts new file mode 100644 index 0000000..88bb89a --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/lazy.d.ts @@ -0,0 +1,2 @@ +export declare function prop(object: object, name: string, f: () => any): void; +export declare function value(f: () => T): () => T; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.cjs new file mode 100644 index 0000000..b84158a --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.cjs @@ -0,0 +1,202 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2ms = p2ms; +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +const OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1 +// input: OP_0 [signatures ...] +// output: m [pubKeys ...] n OP_CHECKMULTISIG +/** + * Represents a function that creates a Pay-to-Multisig (P2MS) payment object. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The created payment object. + * @throws {TypeError} If the provided data is not valid. + */ +function p2ms(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS.OP_0) !== undefined + ); + } + v.parse( + v.partial( + v.object({ + network: v.object({}), + m: v.number(), + n: v.number(), + output: types_js_1.BufferSchema, + pubkeys: v.array( + v.custom(types_js_1.isPoint), + 'Received invalid pubkey', + ), + signatures: v.array( + v.custom(isAcceptableSignature), + 'Expected signature to be of type isAcceptableSignature', + ), + input: types_js_1.BufferSchema, + }), + ), + a, + ); + const network = a.network || networks_js_1.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript.decompile(output); + o.m = chunks[0] - OP_INT_BASE; + o.n = chunks[chunks.length - 2] - OP_INT_BASE; + o.pubkeys = chunks.slice(1, -2); + } + lazy.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript.compile( + [].concat( + OP_INT_BASE + a.m, + a.pubkeys, + OP_INT_BASE + o.n, + OPS.OP_CHECKMULTISIG, + ), + ); + }); + lazy.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript.decompile(a.input).slice(1); + }); + lazy.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript.compile([OPS.OP_0].concat(a.signatures)); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + v.parse(v.number(), chunks[0], { message: 'Output is invalid' }); + v.parse(v.number(), chunks[chunks.length - 2], { + message: 'Output is invalid', + }); + if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => (0, types_js_1.isPoint)(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !(0, types_js_1.stacksEqual)(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if ( + a.signatures && + !(0, types_js_1.stacksEqual)(a.signatures, o.signatures) + ) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.d.ts new file mode 100644 index 0000000..4ec9b69 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2ms.d.ts @@ -0,0 +1,9 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Represents a function that creates a Pay-to-Multisig (P2MS) payment object. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The created payment object. + * @throws {TypeError} If the provided data is not valid. + */ +export declare function p2ms(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.cjs new file mode 100644 index 0000000..65310db --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.cjs @@ -0,0 +1,130 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2pk = p2pk; +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +// input: {signature} +// output: {pubKey} OP_CHECKSIG +/** + * Creates a pay-to-public-key (P2PK) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PK payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +function p2pk(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + output: types_js_1.BufferSchema, + pubkey: v.custom(types_js_1.isPoint, 'invalid pubkey'), + signature: v.custom( + bscript.isCanonicalScriptSignature, + 'Expected signature to be of type isCanonicalScriptSignature', + ), + input: types_js_1.BufferSchema, + }), + ), + a, + ); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || networks_js_1.bitcoin; + const o = { name: 'p2pk', network }; + lazy.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript.compile([a.pubkey, OPS.OP_CHECKSIG]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.signature) return; + return bscript.compile([a.signature]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!(0, types_js_1.isPoint)(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && tools.compare(a.pubkey, o.pubkey) !== 0) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && tools.compare(a.input, o.input) !== 0) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.d.ts new file mode 100644 index 0000000..6f4b13c --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pk.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a pay-to-public-key (P2PK) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PK payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export declare function p2pk(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.cjs new file mode 100644 index 0000000..2ec52c1 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.cjs @@ -0,0 +1,192 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2pkh = p2pkh; +const bcrypto = __importStar(require('../crypto.cjs')); +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const bs58check_1 = __importDefault(require('bs58check')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +// input: {signature} {pubkey} +// output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG +/** + * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PKH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +function p2pkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + address: v.string(), + hash: types_js_1.Hash160bitSchema, + output: (0, types_js_1.NBufferSchemaFactory)(25), + pubkey: v.custom(types_js_1.isPoint), + signature: v.custom(bscript.isCanonicalScriptSignature), + input: types_js_1.BufferSchema, + }), + ), + a, + ); + const _address = lazy.value(() => { + const payload = bs58check_1.default.decode(a.address); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || networks_js_1.bitcoin; + const o = { name: 'p2pkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, network.pubKeyHash); + payload.set(o.hash, 1); + return bs58check_1.default.encode(payload); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([ + OPS.OP_DUP, + OPS.OP_HASH160, + o.hash, + OPS.OP_EQUALVERIFY, + OPS.OP_CHECKSIG, + ]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript.compile([a.signature, a.pubkey]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS.OP_DUP || + a.output[1] !== OPS.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS.OP_EQUALVERIFY || + a.output[24] !== OPS.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!(0, types_js_1.isPoint)(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && tools.compare(a.signature, chunks[0]) !== 0) + throw new TypeError('Signature mismatch'); + if (a.pubkey && tools.compare(a.pubkey, chunks[1]) !== 0) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(chunks[1]); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.d.ts new file mode 100644 index 0000000..e2bdafb --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2pkh.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PKH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export declare function p2pkh(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.cjs new file mode 100644 index 0000000..9793961 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.cjs @@ -0,0 +1,253 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2sh = p2sh; +const bcrypto = __importStar(require('../crypto.cjs')); +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const bs58check_1 = __importDefault(require('bs58check')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +// input: [redeemScriptSig ...] {redeemScript} +// witness: +// output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL +/** + * Creates a Pay-to-Script-Hash (P2SH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2SH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + address: v.string(), + hash: (0, types_js_1.NBufferSchemaFactory)(20), + output: (0, types_js_1.NBufferSchemaFactory)(23), + redeem: v.partial( + v.object({ + network: v.object({}), + output: types_js_1.BufferSchema, + input: types_js_1.BufferSchema, + witness: v.array(types_js_1.BufferSchema), + }), + ), + input: types_js_1.BufferSchema, + witness: v.array(types_js_1.BufferSchema), + }), + ), + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_js_1.bitcoin; + } + const o = { network }; + const _address = lazy.value(() => { + const payload = bs58check_1.default.decode(a.address); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const _redeem = lazy.value(() => { + const chunks = _chunks(); + const lastChunk = chunks[chunks.length - 1]; + return { + network, + output: lastChunk === OPS.OP_FALSE ? Uint8Array.from([]) : lastChunk, + input: bscript.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, o.network.scriptHash); + payload.set(o.hash, 1); + return bs58check_1.default.encode(payload); + }); + lazy.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_HASH160, o.hash, OPS.OP_EQUAL]); + }); + // input dependents + lazy.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript.compile( + [].concat(bscript.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + if (redeem.output.byteLength > 520) + throw new TypeError( + 'Redeem.output unspendable if larger than 520 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = bcrypto.hash160(redeem.output); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript.decompile(redeem.input); + if (!bscript.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!(_redeem().output instanceof Uint8Array)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if ( + a.redeem.output && + tools.compare(a.redeem.output, redeem.output) !== 0 + ) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && tools.compare(a.redeem.input, redeem.input) !== 0) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !(0, types_js_1.stacksEqual)(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.d.ts new file mode 100644 index 0000000..444c394 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2sh.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a Pay-to-Script-Hash (P2SH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2SH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export declare function p2sh(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.cjs new file mode 100644 index 0000000..c2c1c74 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.cjs @@ -0,0 +1,348 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2tr = p2tr; +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const ecc_lib_js_1 = require('../ecc_lib.cjs'); +const bip341_js_1 = require('./bip341.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const bech32_1 = require('bech32'); +const address_js_1 = require('../address.cjs'); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +const TAPROOT_WITNESS_VERSION = 0x01; +const ANNEX_PREFIX = 0x50; +/** + * Creates a Pay-to-Taproot (P2TR) payment object. + * + * @param a - The payment object containing the necessary data for P2TR. + * @param opts - Optional payment options. + * @returns The P2TR payment object. + * @throws {TypeError} If the provided data is invalid or insufficient. + */ +function p2tr(a, opts) { + if ( + !a.address && + !a.output && + !a.pubkey && + !a.internalPubkey && + !(a.witness && a.witness.length > 1) + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + address: v.string(), + input: (0, types_js_1.NBufferSchemaFactory)(0), + network: v.object({}), + output: (0, types_js_1.NBufferSchemaFactory)(34), + internalPubkey: (0, types_js_1.NBufferSchemaFactory)(32), + hash: (0, types_js_1.NBufferSchemaFactory)(32), // merkle root hash, the tweak + pubkey: (0, types_js_1.NBufferSchemaFactory)(32), // tweaked with `hash` from `internalPubkey` + signature: v.union([ + (0, types_js_1.NBufferSchemaFactory)(64), + (0, types_js_1.NBufferSchemaFactory)(65), + ]), + witness: v.array(types_js_1.BufferSchema), + scriptTree: v.custom( + types_js_1.isTaptree, + 'Taptree is not of type isTaptree', + ), + redeem: v.partial( + v.object({ + output: types_js_1.BufferSchema, // tapleaf script + redeemVersion: v.number(), // tapleaf version + witness: v.array(types_js_1.BufferSchema), + }), + ), + redeemVersion: v.number(), + }), + ), + a, + ); + const _address = lazy.value(() => { + return (0, address_js_1.fromBech32)(a.address); + }); + // remove annex if present, ignored by taproot + const _witness = lazy.value(() => { + if (!a.witness || !a.witness.length) return; + if ( + a.witness.length >= 2 && + a.witness[a.witness.length - 1][0] === ANNEX_PREFIX + ) { + return a.witness.slice(0, -1); + } + return a.witness.slice(); + }); + const _hashTree = lazy.value(() => { + if (a.scriptTree) return (0, bip341_js_1.toHashTree)(a.scriptTree); + if (a.hash) return { hash: a.hash }; + return; + }); + const network = a.network || networks_js_1.bitcoin; + const o = { name: 'p2tr', network }; + lazy.prop(o, 'address', () => { + if (!o.pubkey) return; + const words = bech32_1.bech32m.toWords(o.pubkey); + words.unshift(TAPROOT_WITNESS_VERSION); + return bech32_1.bech32m.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + const hashTree = _hashTree(); + if (hashTree) return hashTree.hash; + const w = _witness(); + if (w && w.length > 1) { + const controlBlock = w[w.length - 1]; + const leafVersion = controlBlock[0] & types_js_1.TAPLEAF_VERSION_MASK; + const script = w[w.length - 2]; + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: script, + version: leafVersion, + }); + return (0, bip341_js_1.rootHashFromPath)(controlBlock, leafHash); + } + return null; + }); + lazy.prop(o, 'output', () => { + if (!o.pubkey) return; + return bscript.compile([OPS.OP_1, o.pubkey]); + }); + lazy.prop(o, 'redeemVersion', () => { + if (a.redeemVersion) return a.redeemVersion; + if ( + a.redeem && + a.redeem.redeemVersion !== undefined && + a.redeem.redeemVersion !== null + ) { + return a.redeem.redeemVersion; + } + return bip341_js_1.LEAF_VERSION_TAPSCRIPT; + }); + lazy.prop(o, 'redeem', () => { + const witness = _witness(); // witness without annex + if (!witness || witness.length < 2) return; + return { + output: witness[witness.length - 2], + witness: witness.slice(0, -2), + redeemVersion: + witness[witness.length - 1][0] & types_js_1.TAPLEAF_VERSION_MASK, + }; + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.internalPubkey) { + const tweakedKey = (0, bip341_js_1.tweakKey)(o.internalPubkey, o.hash); + if (tweakedKey) return tweakedKey.x; + } + }); + lazy.prop(o, 'internalPubkey', () => { + if (a.internalPubkey) return a.internalPubkey; + const witness = _witness(); + if (witness && witness.length > 1) + return witness[witness.length - 1].slice(1, 33); + }); + lazy.prop(o, 'signature', () => { + if (a.signature) return a.signature; + const witness = _witness(); // witness without annex + if (!witness || witness.length !== 1) return; + return witness[0]; + }); + lazy.prop(o, 'witness', () => { + if (a.witness) return a.witness; + const hashTree = _hashTree(); + if (hashTree && a.redeem && a.redeem.output && a.internalPubkey) { + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: a.redeem.output, + version: o.redeemVersion, + }); + const path = (0, bip341_js_1.findScriptPath)(hashTree, leafHash); + if (!path) return; + const outputKey = (0, bip341_js_1.tweakKey)( + a.internalPubkey, + hashTree.hash, + ); + if (!outputKey) return; + const controlBock = tools.concat( + [ + Uint8Array.from([o.redeemVersion | outputKey.parity]), + a.internalPubkey, + ].concat(path), + ); + return [a.redeem.output, controlBock]; + } + if (a.signature) return [a.signature]; + }); + // extended validation + if (opts.validate) { + let pubkey = Uint8Array.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== TAPROOT_WITNESS_VERSION) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + pubkey = _address().data; + } + if (a.pubkey) { + if (pubkey.length > 0 && tools.compare(pubkey, a.pubkey) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.pubkey; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_1 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + if (pubkey.length > 0 && tools.compare(pubkey, a.output.slice(2)) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.output.slice(2); + } + if (a.internalPubkey) { + const tweakedKey = (0, bip341_js_1.tweakKey)(a.internalPubkey, o.hash); + if (pubkey.length > 0 && tools.compare(pubkey, tweakedKey.x) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = tweakedKey.x; + } + if (pubkey && pubkey.length) { + if (!(0, ecc_lib_js_1.getEccLib)().isXOnlyPoint(pubkey)) + throw new TypeError('Invalid pubkey for p2tr'); + } + const hashTree = _hashTree(); + if (a.hash && hashTree) { + if (tools.compare(a.hash, hashTree.hash) !== 0) + throw new TypeError('Hash mismatch'); + } + if (a.redeem && a.redeem.output && hashTree) { + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: a.redeem.output, + version: o.redeemVersion, + }); + if (!(0, bip341_js_1.findScriptPath)(hashTree, leafHash)) + throw new TypeError('Redeem script not in tree'); + } + const witness = _witness(); + // compare the provided redeem data with the one computed from witness + if (a.redeem && o.redeem) { + if (a.redeem.redeemVersion) { + if (a.redeem.redeemVersion !== o.redeem.redeemVersion) + throw new TypeError('Redeem.redeemVersion and witness mismatch'); + } + if (a.redeem.output) { + if (bscript.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // output redeem is constructed from the witness + if ( + o.redeem.output && + tools.compare(a.redeem.output, o.redeem.output) !== 0 + ) + throw new TypeError('Redeem.output and witness mismatch'); + } + if (a.redeem.witness) { + if ( + o.redeem.witness && + !(0, types_js_1.stacksEqual)(a.redeem.witness, o.redeem.witness) + ) + throw new TypeError('Redeem.witness and witness mismatch'); + } + } + if (witness && witness.length) { + if (witness.length === 1) { + // key spending + if (a.signature && tools.compare(a.signature, witness[0]) !== 0) + throw new TypeError('Signature mismatch'); + } else { + // script path spending + const controlBlock = witness[witness.length - 1]; + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + if ((controlBlock.length - 33) % 32 !== 0) + throw new TypeError( + `The control-block length of ${controlBlock.length} is incorrect!`, + ); + const m = (controlBlock.length - 33) / 32; + if (m > 128) + throw new TypeError( + `The script path is too long. Got ${m}, expected max 128.`, + ); + const internalPubkey = controlBlock.slice(1, 33); + if ( + a.internalPubkey && + tools.compare(a.internalPubkey, internalPubkey) !== 0 + ) + throw new TypeError('Internal pubkey mismatch'); + if (!(0, ecc_lib_js_1.getEccLib)().isXOnlyPoint(internalPubkey)) + throw new TypeError('Invalid internalPubkey for p2tr witness'); + const leafVersion = controlBlock[0] & types_js_1.TAPLEAF_VERSION_MASK; + const script = witness[witness.length - 2]; + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: script, + version: leafVersion, + }); + const hash = (0, bip341_js_1.rootHashFromPath)(controlBlock, leafHash); + const outputKey = (0, bip341_js_1.tweakKey)(internalPubkey, hash); + if (!outputKey) + // todo: needs test data + throw new TypeError('Invalid outputKey for p2tr witness'); + if (pubkey.length && tools.compare(pubkey, outputKey.x) !== 0) + throw new TypeError('Pubkey mismatch for p2tr witness'); + if (outputKey.parity !== (controlBlock[0] & 1)) + throw new Error('Incorrect parity'); + } + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.d.ts new file mode 100644 index 0000000..2030f62 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2tr.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a Pay-to-Taproot (P2TR) payment object. + * + * @param a - The payment object containing the necessary data for P2TR. + * @param opts - Optional payment options. + * @returns The P2TR payment object. + * @throws {TypeError} If the provided data is invalid or insufficient. + */ +export declare function p2tr(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.cjs new file mode 100644 index 0000000..4ad3cdb --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.cjs @@ -0,0 +1,186 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2wpkh = p2wpkh; +const bcrypto = __importStar(require('../crypto.cjs')); +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const bech32_1 = require('bech32'); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +const EMPTY_BUFFER = new Uint8Array(0); +// witness: {signature} {pubKey} +// input: <> +// output: OP_0 {pubKeyHash} +/** + * Creates a pay-to-witness-public-key-hash (p2wpkh) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The p2wpkh payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +function p2wpkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + address: v.string(), + hash: (0, types_js_1.NBufferSchemaFactory)(20), + input: (0, types_js_1.NBufferSchemaFactory)(0), + network: v.object({}), + output: (0, types_js_1.NBufferSchemaFactory)(22), + pubkey: v.custom(types_js_1.isPoint, 'Not a valid pubkey'), + signature: v.custom(bscript.isCanonicalScriptSignature), + witness: v.array(types_js_1.BufferSchema), + }), + ), + a, + ); + const _address = lazy.value(() => { + const result = bech32_1.bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32_1.bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; + }); + const network = a.network || networks_js_1.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32_1.bech32.toWords(o.hash); + words.unshift(0x00); + return bech32_1.bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && tools.compare(hash, a.output.slice(2)) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!(0, types_js_1.isPoint)(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!(0, types_js_1.isPoint)(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && tools.compare(a.signature, a.witness[0]) !== 0) + throw new TypeError('Signature mismatch'); + // if (a.pubkey && !a.pubkey.equals(a.witness[1])) + if (a.pubkey && tools.compare(a.pubkey, a.witness[1]) !== 0) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(a.witness[1]); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.d.ts new file mode 100644 index 0000000..e4817a1 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wpkh.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a pay-to-witness-public-key-hash (p2wpkh) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The p2wpkh payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +export declare function p2wpkh(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.cjs new file mode 100644 index 0000000..97c63d4 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.cjs @@ -0,0 +1,269 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2wsh = p2wsh; +const sha256_1 = require('@noble/hashes/sha256'); +const networks_js_1 = require('../networks.cjs'); +const bscript = __importStar(require('../script.cjs')); +const types_js_1 = require('../types.cjs'); +const lazy = __importStar(require('./lazy.cjs')); +const bech32_1 = require('bech32'); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OPS = bscript.OPS; +const EMPTY_BUFFER = new Uint8Array(0); +function chunkHasUncompressedPubkey(chunk) { + if ( + chunk instanceof Uint8Array && + chunk.length === 65 && + chunk[0] === 0x04 && + (0, types_js_1.isPoint)(chunk) + ) { + return true; + } else { + return false; + } +} +// input: <> +// witness: [redeemScriptSig ...] {redeemScript} +// output: OP_0 {sha256(redeemScript)} +/** + * Creates a Pay-to-Witness-Script-Hash (P2WSH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2WSH payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + (0, types_js_1.NullablePartial)({ + network: v.object({}), + address: v.string(), + hash: types_js_1.Buffer256bitSchema, + output: (0, types_js_1.NBufferSchemaFactory)(34), + redeem: (0, types_js_1.NullablePartial)({ + input: types_js_1.BufferSchema, + network: v.object({}), + output: types_js_1.BufferSchema, + witness: v.array(types_js_1.BufferSchema), + }), + input: (0, types_js_1.NBufferSchemaFactory)(0), + witness: v.array(types_js_1.BufferSchema), + }), + a, + ); + const _address = lazy.value(() => { + const result = bech32_1.bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32_1.bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_js_1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32_1.bech32.toWords(o.hash); + words.unshift(0x00); + return bech32_1.bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) + return (0, sha256_1.sha256)(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty/valid? + if (a.redeem.output) { + const decompile = bscript.decompile(a.redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output is invalid'); + if (a.redeem.output.byteLength > 3600) + throw new TypeError( + 'Redeem.output unspendable if larger than 3600 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = (0, sha256_1.sha256)(a.redeem.output); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !(0, types_js_1.stacksEqual)(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if ( + a.redeem && + a.redeem.output && + tools.compare(a.redeem.output, wScript) !== 0 + ) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.d.ts new file mode 100644 index 0000000..315f55f --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/payments/p2wsh.d.ts @@ -0,0 +1,10 @@ +import { Payment, PaymentOpts } from './index.js'; +/** + * Creates a Pay-to-Witness-Script-Hash (P2WSH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2WSH payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +export declare function p2wsh(a: Payment, opts?: PaymentOpts): Payment; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.cjs new file mode 100644 index 0000000..b6b28e6 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.cjs @@ -0,0 +1,1797 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Psbt = void 0; +const bip174_1 = require('bip174'); +const varuint = __importStar(require('varuint-bitcoin')); +const bip174_2 = require('bip174'); +const address_js_1 = require('./address.cjs'); +const bufferutils_js_1 = require('./bufferutils.cjs'); +const networks_js_1 = require('./networks.cjs'); +const payments = __importStar(require('./payments/index.cjs')); +const bip341_js_1 = require('./payments/bip341.cjs'); +const bscript = __importStar(require('./script.cjs')); +const transaction_js_1 = require('./transaction.cjs'); +const bip371_js_1 = require('./psbt/bip371.cjs'); +const psbtutils_js_1 = require('./psbt/psbtutils.cjs'); +const tools = __importStar(require('uint8array-tools')); +/** + * These are the default arguments for a Psbt instance. + */ +const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_js_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, // satoshi per byte +}; +/** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ +class Psbt { + data; + static fromBase64(data, opts = {}) { + const buffer = tools.fromBase64(data); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = tools.fromHex(data); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + __CACHE; + opts; + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Psbt's predecessor (TransactionBuilder - now removed) behavior + // was to not confirm input values before signing. + // Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: (0, bufferutils_js_1.cloneBuffer)(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = (0, address_js_1.fromOutputScript)( + output.script, + this.opts.network, + ); + } catch (_) {} + return { + script: (0, bufferutils_js_1.cloneBuffer)(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + (0, bip371_js_1.checkTaprootInputFields)(inputData, inputData, 'addInput'); + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = (0, address_js_1.toOutputScript)(address, network); + outputData = Object.assign({}, outputData, { script }); + } + (0, bip371_js_1.checkTaprootOutputFields)( + outputData, + outputData, + 'addOutput', + ); + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + (0, bip174_2.checkForInput)(this.data.inputs, 0); // making sure we have at least one + range(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc) { + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + undefined, + finalScriptsFunc, + ); + return this._finalizeInput(inputIndex, input, finalScriptsFunc); + } + finalizeTaprootInput( + inputIndex, + tapLeafHashToFinalize, + finalScriptsFunc = bip371_js_1.tapScriptFinalizer, + ) { + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc, + ); + throw new Error(`Cannot finalize input #${inputIndex}. Not Taproot.`); + } + _finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts) { + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + _finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc = bip371_js_1.tapScriptFinalizer, + ) { + if (!input.witnessUtxo) + throw new Error( + `Cannot finalize input #${inputIndex}. Missing withness utxo.`, + ); + // Check key spend first. Increased privacy and reduced block space. + if (input.tapKeySig) { + const payment = payments.p2tr({ + output: input.witnessUtxo.script, + signature: input.tapKeySig, + }); + const finalScriptWitness = (0, + psbtutils_js_1.witnessStackToScriptWitness)(payment.witness); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } else { + const { finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + tapLeafHashToFinalize, + ); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = (0, bip174_2.checkForOutput)(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = (0, bip174_2.checkForOutput)(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs(validator) { + (0, bip174_2.checkForInput)(this.data.inputs, 0); // making sure we have at least one + const results = range(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx, validator), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + if ((0, bip371_js_1.isTaprootInput)(input)) + return this.validateSignaturesOfTaprootInput( + inputIndex, + validator, + pubkey, + ); + return this._validateSignaturesOfInput(inputIndex, validator, pubkey); + } + _validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + const mySigs = pubkey + ? partialSig.filter(sig => tools.compare(sig.pubkey, pubkey) === 0) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + results.push(validator(pSig.pubkey, hash, sig.signature)); + } + return results.every(res => res === true); + } + validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const tapKeySig = (input || {}).tapKeySig; + const tapScriptSig = (input || {}).tapScriptSig; + if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length)) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + pubkey = pubkey && (0, bip371_js_1.toXOnly)(pubkey); + const allHashses = pubkey + ? getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + pubkey, + this.__CACHE, + ) + : getAllTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + this.__CACHE, + ); + if (!allHashses.length) throw new Error('No signatures for this pubkey'); + const tapKeyHash = allHashses.find(h => !h.leafHash); + let validationResultCount = 0; + if (tapKeySig && tapKeyHash) { + const isValidTapkeySig = validator( + tapKeyHash.pubkey, + tapKeyHash.hash, + trimTaprootSig(tapKeySig), + ); + if (!isValidTapkeySig) return false; + validationResultCount++; + } + if (tapScriptSig) { + for (const tapSig of tapScriptSig) { + const tapSigHash = allHashses.find( + h => tools.compare(h.pubkey, tapSig.pubkey) === 0, + ); + if (tapSigHash) { + const isValidTapScriptSig = validator( + tapSig.pubkey, + tapSigHash.hash, + trimTaprootSig(tapSig.signature), + ); + if (!isValidTapScriptSig) return false; + validationResultCount++; + } + } + } + return validationResultCount > 0; + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs(keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync(keyPair, sighashTypes) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput(inputIndex, keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) { + return this._signTaprootInput( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + } + return this._signInput(inputIndex, keyPair, sighashTypes); + } + signTaprootInput(inputIndex, keyPair, tapLeafHashToSign, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) + return this._signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + } + _signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + _signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes = [transaction_js_1.Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ); + const tapKeySig = hashesForSig + .filter(h => !h.leafHash) + .map(h => + (0, bip371_js_1.serializeTaprootSignature)( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + )[0]; + const tapScriptSig = hashesForSig + .filter(h => !!h.leafHash) + .map(h => ({ + pubkey: (0, bip371_js_1.toXOnly)(keyPair.publicKey), + signature: (0, bip371_js_1.serializeTaprootSignature)( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + leafHash: h.leafHash, + })); + if (tapKeySig) { + this.data.updateInput(inputIndex, { tapKeySig }); + } + if (tapScriptSig.length) { + this.data.updateInput(inputIndex, { tapScriptSig }); + } + return this; + } + signInputAsync(inputIndex, keyPair, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + return this._signInputAsync(inputIndex, keyPair, sighashTypes); + }); + } + signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, bip174_2.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_js_1.isTaprootInput)(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + }); + } + _signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_ALL], + ) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + } + async _signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes = [transaction_js_1.Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + const signaturePromises = []; + const tapKeyHash = hashesForSig.filter(h => !h.leafHash)[0]; + if (tapKeyHash) { + const tapKeySigPromise = Promise.resolve( + keyPair.signSchnorr(tapKeyHash.hash), + ).then(sig => { + return { + tapKeySig: (0, bip371_js_1.serializeTaprootSignature)( + sig, + input.sighashType, + ), + }; + }); + signaturePromises.push(tapKeySigPromise); + } + const tapScriptHashes = hashesForSig.filter(h => !!h.leafHash); + if (tapScriptHashes.length) { + const tapScriptSigPromises = tapScriptHashes.map(tsh => { + return Promise.resolve(keyPair.signSchnorr(tsh.hash)).then( + signature => { + const tapScriptSig = [ + { + pubkey: (0, bip371_js_1.toXOnly)(keyPair.publicKey), + signature: (0, bip371_js_1.serializeTaprootSignature)( + signature, + input.sighashType, + ), + leafHash: tsh.leafHash, + }, + ]; + return { tapScriptSig }; + }, + ); + }); + signaturePromises.push(...tapScriptSigPromises); + } + return Promise.all(signaturePromises).then(results => { + results.forEach(v => this.data.updateInput(inputIndex, v)); + }); + } + checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ) { + if (typeof keyPair.signSchnorr !== 'function') + throw new Error( + `Need Schnorr Signer to sign taproot input #${inputIndex}.`, + ); + const hashesForSig = getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + keyPair.publicKey, + this.__CACHE, + tapLeafHashToSign, + allowedSighashTypes, + ); + if (!hashesForSig || !hashesForSig.length) + throw new Error( + `Can not sign for input #${inputIndex} with the key ${tools.toHex(keyPair.publicKey)}`, + ); + return hashesForSig; + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + (0, bip371_js_1.checkTaprootInputFields)( + this.data.inputs[inputIndex], + updateData, + 'updateInput', + ); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + const outputData = this.data.outputs[outputIndex]; + (0, bip371_js_1.checkTaprootOutputFields)( + outputData, + updateData, + 'updateOutput', + ); + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } +} +exports.Psbt = Psbt; +/** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ +const transactionFromBuffer = buffer => new PsbtTransaction(buffer); +/** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ +class PsbtTransaction { + tx; + constructor(buffer = Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_js_1.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!(input.hash instanceof Uint8Array) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? (0, bufferutils_js_1.reverseBuffer)(tools.fromHex(input.hash)) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !(output.script instanceof Uint8Array) || + typeof output.value !== 'bigint' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } +} +function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } +} +function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } +} +function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = compressPubkey(pkey); + return partialSig.find( + pSig => tools.compare(pSig.pubkey, pubkey) === 0, + ); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; +} +function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; +} +function bip32DerivationIsMine(root) { + return d => { + if (tools.compare(root.fingerprint, d.masterFingerprint)) return false; + if (tools.compare(root.derivePath(d.path).publicKey, d.pubkey)) + return false; + return true; + }; +} +function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } +} +function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } +} +function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + const throws = (0, bip371_js_1.isTaprootInput)(input) + ? (0, bip371_js_1.checkTaprootInputForSigs)(input, action) + : (0, psbtutils_js_1.checkInputForSig)(input, action); + if (throws) + throw new Error('Can not modify transaction, signatures exist.'); + }); +} +function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); +} +function checkScriptForPubkey(pubkey, script, action) { + if (!(0, psbtutils_js_1.pubkeyInScript)(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${tools.toHex(pubkey)}`, + ); + } +} +function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } +} +function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); +} +function checkTxInputCache(cache, input) { + const key = + tools.toHex( + (0, bufferutils_js_1.reverseBuffer)(Uint8Array.from(input.hash)), + ) + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; +} +function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (tools.compare(scriptPubKey, redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; +} +const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script'); +const checkWitnessScript = scriptCheckerFactory( + payments.p2wsh, + 'Witness script', +); +function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; +} +function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); +} +function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, +) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = (0, psbtutils_js_1.witnessStackToScriptWitness)( + p2wsh.witness, + ); + } else { + finalScriptWitness = (0, psbtutils_js_1.witnessStackToScriptWitness)( + payment.witness, + ); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; +} +function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, +) { + const input = (0, bip174_2.checkForInput)(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; +} +function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_js_1.Transaction.SIGHASH_ALL; + checkSighashTypeAllowed(sighashType, sighashTypes); + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (tools.compare(prevoutHash, utxoHash) !== 0) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if ((0, psbtutils_js_1.isP2WPKH)(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments.p2pkh({ + hash: meaningfulScript.slice(2), + }).output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${tools.toHex(meaningfulScript)}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + "to trick you into paying large fees. This behavior is the same as Psbt's predecessor " + + '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; +} +function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) { + const allPublicKeys = []; + if (input.tapInternalKey) { + const key = getPrevoutTaprootKey(inputIndex, input, cache); + if (key) { + allPublicKeys.push(key); + } + } + if (input.tapScriptSig) { + const tapScriptPubkeys = input.tapScriptSig.map(tss => tss.pubkey); + allPublicKeys.push(...tapScriptPubkeys); + } + const allHashes = allPublicKeys.map(publicKey => + getTaprootHashesForSig(inputIndex, input, inputs, publicKey, cache), + ); + return allHashes.flat(); +} +function getPrevoutTaprootKey(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return (0, psbtutils_js_1.isP2TR)(script) ? script.subarray(2, 34) : null; +} +function trimTaprootSig(signature) { + return signature.length === 64 ? signature : signature.subarray(0, 64); +} +function getTaprootHashesForSig( + inputIndex, + input, + inputs, + pubkey, + cache, + tapLeafHashToSign, + allowedSighashTypes, +) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_js_1.Transaction.SIGHASH_DEFAULT; + checkSighashTypeAllowed(sighashType, allowedSighashTypes); + const prevOuts = inputs.map((i, index) => + getScriptAndAmountFromUtxo(index, i, cache), + ); + const signingScripts = prevOuts.map(o => o.script); + const values = prevOuts.map(o => o.value); + const hashes = []; + if (input.tapInternalKey && !tapLeafHashToSign) { + const outputKey = + getPrevoutTaprootKey(inputIndex, input, cache) || Uint8Array.from([]); + if (tools.compare((0, bip371_js_1.toXOnly)(pubkey), outputKey) === 0) { + const tapKeyHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + sighashType, + ); + hashes.push({ pubkey, hash: tapKeyHash }); + } + } + const tapLeafHashes = (input.tapLeafScript || []) + .filter(tapLeaf => + (0, psbtutils_js_1.pubkeyInScript)(pubkey, tapLeaf.script), + ) + .map(tapLeaf => { + const hash = (0, bip341_js_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return Object.assign({ hash }, tapLeaf); + }) + .filter( + tapLeaf => + !tapLeafHashToSign || + tools.compare(tapLeafHashToSign, tapLeaf.hash) === 0, + ) + .map(tapLeaf => { + const tapScriptHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + sighashType, + tapLeaf.hash, + ); + return { + pubkey, + hash: tapScriptHash, + leafHash: tapLeaf.hash, + }; + }); + return hashes.concat(tapLeafHashes); +} +function checkSighashTypeAllowed(sighashType, sighashTypes) { + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } +} +function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; +} +function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || (0, psbtutils_js_1.isP2WPKH)(res.script)) { + res.isSegwit = true; + } + return res; +} +function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = (0, bip174_2.checkForInput)(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (tools.compare(bipDv.masterFingerprint, hdKeyPair.fingerprint) === 0) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (tools.compare(bipDv.pubkey, node.publicKey) !== 0) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; +} +function getSortedSigs(script, partialSig) { + const p2ms = payments.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return tools.compare(ps.pubkey, pk) === 0; + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); +} +function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.encodingLength(vi.bigintValue); + return vi.numberValue; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); +} +function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_js_1.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_js_1.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_js_1.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_js_1.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; +} +function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_js_1.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); +} +function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0n; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0n); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(Number(fee / BigInt(bytes))); +} +function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; +} +function getScriptFromUtxo(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return script; +} +function getScriptAndAmountFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return { + script: input.witnessUtxo.script, + value: input.witnessUtxo.value, + }; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const o = nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index]; + return { script: o.script, value: o.value }; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } +} +function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return (0, psbtutils_js_1.pubkeyInScript)(pubkey, meaningfulScript); +} +function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return (0, psbtutils_js_1.pubkeyInScript)(pubkey, meaningfulScript); +} +function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !(lastItem instanceof Uint8Array) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function compressPubkey(pubkey) { + if (pubkey.length === 65) { + const parity = pubkey[64] & 1; + const newKey = pubkey.slice(0, 33); + newKey[0] = 2 | parity; + return newKey; + } + return pubkey.slice(); +} +function isPubkeyLike(buf) { + return buf.length === 33 && bscript.isCanonicalPubKey(buf); +} +function isSigLike(buf) { + return bscript.isCanonicalScriptSignature(buf); +} +function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, +) { + const isP2SH = (0, psbtutils_js_1.isP2SHScript)(script); + const isP2SHP2WSH = + isP2SH && redeemScript && (0, psbtutils_js_1.isP2WSHScript)(redeemScript); + const isP2WSH = (0, psbtutils_js_1.isP2WSHScript)(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; +} +function checkInvalidP2WSH(script) { + if ( + (0, psbtutils_js_1.isP2WPKH)(script) || + (0, psbtutils_js_1.isP2SHScript)(script) + ) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } +} +function classifyScript(script) { + if ((0, psbtutils_js_1.isP2WPKH)(script)) return 'witnesspubkeyhash'; + if ((0, psbtutils_js_1.isP2PKH)(script)) return 'pubkeyhash'; + if ((0, psbtutils_js_1.isP2MS)(script)) return 'multisig'; + if ((0, psbtutils_js_1.isP2PK)(script)) return 'pubkey'; + return 'nonstandard'; +} +function range(n) { + return [...Array(n).keys()]; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.d.ts new file mode 100644 index 0000000..4e2da7f --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt.d.ts @@ -0,0 +1,205 @@ +import { Psbt as PsbtBase } from 'bip174'; +import { KeyValue, PsbtGlobalUpdate, PsbtInput, PsbtInputUpdate, PsbtOutput, PsbtOutputUpdate } from 'bip174'; +import { Network } from './networks.js'; +import { Transaction } from './transaction.js'; +export interface TransactionInput { + hash: string | Uint8Array; + index: number; + sequence?: number; +} +export interface PsbtTxInput extends TransactionInput { + hash: Uint8Array; +} +export interface TransactionOutput { + script: Uint8Array; + value: bigint; +} +export interface PsbtTxOutput extends TransactionOutput { + address: string | undefined; +} +export type ValidateSigFunction = (pubkey: Uint8Array, msghash: Uint8Array, signature: Uint8Array) => boolean; +/** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ +export declare class Psbt { + readonly data: PsbtBase; + static fromBase64(data: string, opts?: PsbtOptsOptional): Psbt; + static fromHex(data: string, opts?: PsbtOptsOptional): Psbt; + static fromBuffer(buffer: Uint8Array, opts?: PsbtOptsOptional): Psbt; + private __CACHE; + private opts; + constructor(opts?: PsbtOptsOptional, data?: PsbtBase); + get inputCount(): number; + get version(): number; + set version(version: number); + get locktime(): number; + set locktime(locktime: number); + get txInputs(): PsbtTxInput[]; + get txOutputs(): PsbtTxOutput[]; + combine(...those: Psbt[]): this; + clone(): Psbt; + setMaximumFeeRate(satoshiPerByte: number): void; + setVersion(version: number): this; + setLocktime(locktime: number): this; + setInputSequence(inputIndex: number, sequence: number): this; + addInputs(inputDatas: PsbtInputExtended[]): this; + addInput(inputData: PsbtInputExtended): this; + addOutputs(outputDatas: PsbtOutputExtended[]): this; + addOutput(outputData: PsbtOutputExtended): this; + extractTransaction(disableFeeCheck?: boolean): Transaction; + getFeeRate(): number; + getFee(): bigint; + finalizeAllInputs(): this; + finalizeInput(inputIndex: number, finalScriptsFunc?: FinalScriptsFunc | FinalTaprootScriptsFunc): this; + finalizeTaprootInput(inputIndex: number, tapLeafHashToFinalize?: Uint8Array, finalScriptsFunc?: FinalTaprootScriptsFunc): this; + private _finalizeInput; + private _finalizeTaprootInput; + getInputType(inputIndex: number): AllScriptType; + inputHasPubkey(inputIndex: number, pubkey: Uint8Array): boolean; + inputHasHDKey(inputIndex: number, root: HDSigner): boolean; + outputHasPubkey(outputIndex: number, pubkey: Uint8Array): boolean; + outputHasHDKey(outputIndex: number, root: HDSigner): boolean; + validateSignaturesOfAllInputs(validator: ValidateSigFunction): boolean; + validateSignaturesOfInput(inputIndex: number, validator: ValidateSigFunction, pubkey?: Uint8Array): boolean; + private _validateSignaturesOfInput; + private validateSignaturesOfTaprootInput; + signAllInputsHD(hdKeyPair: HDSigner, sighashTypes?: number[]): this; + signAllInputsHDAsync(hdKeyPair: HDSigner | HDSignerAsync, sighashTypes?: number[]): Promise; + signInputHD(inputIndex: number, hdKeyPair: HDSigner, sighashTypes?: number[]): this; + signInputHDAsync(inputIndex: number, hdKeyPair: HDSigner | HDSignerAsync, sighashTypes?: number[]): Promise; + signAllInputs(keyPair: Signer, sighashTypes?: number[]): this; + signAllInputsAsync(keyPair: Signer | SignerAsync, sighashTypes?: number[]): Promise; + signInput(inputIndex: number, keyPair: Signer, sighashTypes?: number[]): this; + signTaprootInput(inputIndex: number, keyPair: Signer, tapLeafHashToSign?: Uint8Array, sighashTypes?: number[]): this; + private _signInput; + private _signTaprootInput; + signInputAsync(inputIndex: number, keyPair: Signer | SignerAsync, sighashTypes?: number[]): Promise; + signTaprootInputAsync(inputIndex: number, keyPair: Signer | SignerAsync, tapLeafHash?: Uint8Array, sighashTypes?: number[]): Promise; + private _signInputAsync; + private _signTaprootInputAsync; + private checkTaprootHashesForSig; + toBuffer(): Uint8Array; + toHex(): string; + toBase64(): string; + updateGlobal(updateData: PsbtGlobalUpdate): this; + updateInput(inputIndex: number, updateData: PsbtInputUpdate): this; + updateOutput(outputIndex: number, updateData: PsbtOutputUpdate): this; + addUnknownKeyValToGlobal(keyVal: KeyValue): this; + addUnknownKeyValToInput(inputIndex: number, keyVal: KeyValue): this; + addUnknownKeyValToOutput(outputIndex: number, keyVal: KeyValue): this; + clearFinalizedInput(inputIndex: number): this; +} +interface PsbtOptsOptional { + network?: Network; + maximumFeeRate?: number; +} +interface PsbtInputExtended extends PsbtInput, TransactionInput { +} +type PsbtOutputExtended = PsbtOutputExtendedAddress | PsbtOutputExtendedScript; +interface PsbtOutputExtendedAddress extends PsbtOutput { + address: string; + value: bigint; +} +interface PsbtOutputExtendedScript extends PsbtOutput { + script: Uint8Array; + value: bigint; +} +interface HDSignerBase { + /** + * DER format compressed publicKey buffer + */ + publicKey: Uint8Array; + /** + * The first 4 bytes of the sha256-ripemd160 of the publicKey + */ + fingerprint: Uint8Array; +} +export interface HDSigner extends HDSignerBase { + /** + * The path string must match /^m(\/\d+'?)+$/ + * ex. m/44'/0'/0'/1/23 levels with ' must be hard derivations + */ + derivePath(path: string): HDSigner; + /** + * Input hash (the "message digest") for the signature algorithm + * Return a 64 byte signature (32 byte r and 32 byte s in that order) + */ + sign(hash: Uint8Array): Uint8Array; +} +/** + * Same as above but with async sign method + */ +export interface HDSignerAsync extends HDSignerBase { + derivePath(path: string): HDSignerAsync; + sign(hash: Uint8Array): Promise; +} +export interface Signer { + publicKey: Uint8Array; + network?: any; + sign(hash: Uint8Array, lowR?: boolean): Uint8Array; + signSchnorr?(hash: Uint8Array): Uint8Array; + getPublicKey?(): Uint8Array; +} +export interface SignerAsync { + publicKey: Uint8Array; + network?: any; + sign(hash: Uint8Array, lowR?: boolean): Promise; + signSchnorr?(hash: Uint8Array): Promise; + getPublicKey?(): Uint8Array; +} +/** + * This function must do two things: + * 1. Check if the `input` can be finalized. If it can not be finalized, throw. + * ie. `Can not finalize input #${inputIndex}` + * 2. Create the finalScriptSig and finalScriptWitness Buffers. + */ +type FinalScriptsFunc = (inputIndex: number, // Which input is it? +input: PsbtInput, // The PSBT input contents +script: Uint8Array, // The "meaningful" locking script Buffer (redeemScript for P2SH etc.) +isSegwit: boolean, // Is it segwit? +isP2SH: boolean, // Is it P2SH? +isP2WSH: boolean) => { + finalScriptSig: Uint8Array | undefined; + finalScriptWitness: Uint8Array | undefined; +}; +type FinalTaprootScriptsFunc = (inputIndex: number, // Which input is it? +input: PsbtInput, // The PSBT input contents +tapLeafHashToFinalize?: Uint8Array) => { + finalScriptWitness: Uint8Array | undefined; +}; +type AllScriptType = 'witnesspubkeyhash' | 'pubkeyhash' | 'multisig' | 'pubkey' | 'nonstandard' | 'p2sh-witnesspubkeyhash' | 'p2sh-pubkeyhash' | 'p2sh-multisig' | 'p2sh-pubkey' | 'p2sh-nonstandard' | 'p2wsh-pubkeyhash' | 'p2wsh-multisig' | 'p2wsh-pubkey' | 'p2wsh-nonstandard' | 'p2sh-p2wsh-pubkeyhash' | 'p2sh-p2wsh-multisig' | 'p2sh-p2wsh-pubkey' | 'p2sh-p2wsh-nonstandard'; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.cjs new file mode 100644 index 0000000..e7657dd --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.cjs @@ -0,0 +1,556 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.toXOnly = void 0; +exports.tapScriptFinalizer = tapScriptFinalizer; +exports.serializeTaprootSignature = serializeTaprootSignature; +exports.isTaprootInput = isTaprootInput; +exports.isTaprootOutput = isTaprootOutput; +exports.checkTaprootInputFields = checkTaprootInputFields; +exports.checkTaprootOutputFields = checkTaprootOutputFields; +exports.tweakInternalPubKey = tweakInternalPubKey; +exports.tapTreeToList = tapTreeToList; +exports.tapTreeFromList = tapTreeFromList; +exports.checkTaprootInputForSigs = checkTaprootInputForSigs; +const types_js_1 = require('../types.cjs'); +const transaction_js_1 = require('../transaction.cjs'); +const psbtutils_js_1 = require('./psbtutils.cjs'); +const bip341_js_1 = require('../payments/bip341.cjs'); +const index_js_1 = require('../payments/index.cjs'); +const tools = __importStar(require('uint8array-tools')); +const psbtutils_js_2 = require('./psbtutils.cjs'); +/** + * Converts a public key to an X-only public key. + * @param pubKey The public key to convert. + * @returns The X-only public key. + */ +const toXOnly = pubKey => (pubKey.length === 32 ? pubKey : pubKey.slice(1, 33)); +exports.toXOnly = toXOnly; +/** + * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided. + * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path. + * @param inputIndex the position of the PSBT input. + * @param input the PSBT input. + * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash + * and will try to build the finalScriptWitness. + * @returns the finalScriptWitness or throws an exception if no tapleaf found. + */ +function tapScriptFinalizer(inputIndex, input, tapLeafHashToFinalize) { + const tapLeaf = findTapLeafToFinalize( + input, + inputIndex, + tapLeafHashToFinalize, + ); + try { + const sigs = sortSignatures(input, tapLeaf); + const witness = sigs.concat(tapLeaf.script).concat(tapLeaf.controlBlock); + return { + finalScriptWitness: (0, psbtutils_js_1.witnessStackToScriptWitness)( + witness, + ), + }; + } catch (err) { + throw new Error(`Can not finalize taproot input #${inputIndex}: ${err}`); + } +} +/** + * Serializes a taproot signature. + * @param sig The signature to serialize. + * @param sighashType The sighash type. Optional. + * @returns The serialized taproot signature. + */ +function serializeTaprootSignature(sig, sighashType) { + const sighashTypeByte = sighashType + ? Uint8Array.from([sighashType]) + : Uint8Array.from([]); + return tools.concat([sig, sighashTypeByte]); +} +/** + * Checks if a PSBT input is a taproot input. + * @param input The PSBT input to check. + * @returns True if the input is a taproot input, false otherwise. + */ +function isTaprootInput(input) { + return ( + input && + !!( + input.tapInternalKey || + input.tapMerkleRoot || + (input.tapLeafScript && input.tapLeafScript.length) || + (input.tapBip32Derivation && input.tapBip32Derivation.length) || + (input.witnessUtxo && + (0, psbtutils_js_1.isP2TR)(input.witnessUtxo.script)) + ) + ); +} +/** + * Checks if a PSBT output is a taproot output. + * @param output The PSBT output to check. + * @param script The script to check. Optional. + * @returns True if the output is a taproot output, false otherwise. + */ +function isTaprootOutput(output, script) { + return ( + output && + !!( + output.tapInternalKey || + output.tapTree || + (output.tapBip32Derivation && output.tapBip32Derivation.length) || + (script && (0, psbtutils_js_1.isP2TR)(script)) + ) + ); +} +/** + * Checks the taproot input fields for consistency. + * @param inputData The original input data. + * @param newInputData The new input data. + * @param action The action being performed. + * @throws Throws an error if the input fields are inconsistent. + */ +function checkTaprootInputFields(inputData, newInputData, action) { + checkMixedTaprootAndNonTaprootInputFields(inputData, newInputData, action); + checkIfTapLeafInTree(inputData, newInputData, action); +} +/** + * Checks the taproot output fields for consistency. + * @param outputData The original output data. + * @param newOutputData The new output data. + * @param action The action being performed. + * @throws Throws an error if the output fields are inconsistent. + */ +function checkTaprootOutputFields(outputData, newOutputData, action) { + checkMixedTaprootAndNonTaprootOutputFields(outputData, newOutputData, action); + checkTaprootScriptPubkey(outputData, newOutputData); +} +function checkTaprootScriptPubkey(outputData, newOutputData) { + if (!newOutputData.tapTree && !newOutputData.tapInternalKey) return; + const tapInternalKey = + newOutputData.tapInternalKey || outputData.tapInternalKey; + const tapTree = newOutputData.tapTree || outputData.tapTree; + if (tapInternalKey) { + const { script: scriptPubkey } = outputData; + const script = getTaprootScripPubkey(tapInternalKey, tapTree); + if (scriptPubkey && tools.compare(script, scriptPubkey) !== 0) + throw new Error('Error adding output. Script or address mismatch.'); + } +} +/** + * Returns the Taproot script public key. + * + * @param tapInternalKey - The Taproot internal key. + * @param tapTree - The Taproot tree (optional). + * @returns The Taproot script public key. + */ +function getTaprootScripPubkey(tapInternalKey, tapTree) { + const scriptTree = tapTree && tapTreeFromList(tapTree.leaves); + const { output } = (0, index_js_1.p2tr)({ + internalPubkey: tapInternalKey, + scriptTree, + }); + return output; +} +/** + * Tweak the internal public key for a specific input. + * @param inputIndex - The index of the input. + * @param input - The PsbtInput object representing the input. + * @returns The tweaked internal public key. + * @throws Error if the tap internal key cannot be tweaked. + */ +function tweakInternalPubKey(inputIndex, input) { + const tapInternalKey = input.tapInternalKey; + const outputKey = + tapInternalKey && + (0, bip341_js_1.tweakKey)(tapInternalKey, input.tapMerkleRoot); + if (!outputKey) + throw new Error( + `Cannot tweak tap internal key for input #${inputIndex}. Public key: ${ + // tapInternalKey && tapInternalKey.toString('hex') + tapInternalKey && tools.toHex(tapInternalKey) + }`, + ); + return outputKey.x; +} +/** + * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @param tree the binary tap tree + * @returns a list of BIP 371 tapleaves + */ +function tapTreeToList(tree) { + if (!(0, types_js_1.isTaptree)(tree)) + throw new Error( + 'Cannot convert taptree to tapleaf list. Expecting a tapree structure.', + ); + return _tapTreeToList(tree); +} +/** + * Convert a BIP371 TapLeaf list to a TapTree (binary). + * @param leaves a list of tapleaves where each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed + */ +function tapTreeFromList(leaves = []) { + if (leaves.length === 1 && leaves[0].depth === 0) + return { + output: leaves[0].script, + version: leaves[0].leafVersion, + }; + return instertLeavesInTree(leaves); +} +/** + * Checks the taproot input for signatures. + * @param input The PSBT input to check. + * @param action The action being performed. + * @returns True if the input has taproot signatures, false otherwise. + */ +function checkTaprootInputForSigs(input, action) { + const sigs = extractTaprootSigs(input); + return sigs.some(sig => + (0, psbtutils_js_2.signatureBlocksAction)( + sig, + decodeSchnorrSignature, + action, + ), + ); +} +/** + * Decodes a Schnorr signature. + * @param signature The signature to decode. + * @returns The decoded Schnorr signature. + */ +function decodeSchnorrSignature(signature) { + return { + signature: signature.slice(0, 64), + hashType: + signature.slice(64)[0] || transaction_js_1.Transaction.SIGHASH_DEFAULT, + }; +} +/** + * Extracts taproot signatures from a PSBT input. + * @param input The PSBT input to extract signatures from. + * @returns An array of taproot signatures. + */ +function extractTaprootSigs(input) { + const sigs = []; + if (input.tapKeySig) sigs.push(input.tapKeySig); + if (input.tapScriptSig) + sigs.push(...input.tapScriptSig.map(s => s.signature)); + if (!sigs.length) { + const finalTapKeySig = getTapKeySigFromWithness(input.finalScriptWitness); + if (finalTapKeySig) sigs.push(finalTapKeySig); + } + return sigs; +} +/** + * Gets the taproot signature from the witness. + * @param finalScriptWitness The final script witness. + * @returns The taproot signature, or undefined if not found. + */ +function getTapKeySigFromWithness(finalScriptWitness) { + if (!finalScriptWitness) return; + const witness = finalScriptWitness.slice(2); + // todo: add schnorr signature validation + if (witness.length === 64 || witness.length === 65) return witness; +} +/** + * Converts a binary tree to a BIP371 type list. + * @param tree The binary tap tree. + * @param leaves A list of tapleaves. Optional. + * @param depth The current depth. Optional. + * @returns A list of BIP 371 tapleaves. + * @throws Throws an error if the taptree cannot be converted to a tapleaf list. + */ +function _tapTreeToList(tree, leaves = [], depth = 0) { + if (depth > bip341_js_1.MAX_TAPTREE_DEPTH) + throw new Error('Max taptree depth exceeded.'); + if (!tree) return []; + if ((0, types_js_1.isTapleaf)(tree)) { + leaves.push({ + depth, + leafVersion: tree.version || bip341_js_1.LEAF_VERSION_TAPSCRIPT, + script: tree.output, + }); + return leaves; + } + if (tree[0]) _tapTreeToList(tree[0], leaves, depth + 1); + if (tree[1]) _tapTreeToList(tree[1], leaves, depth + 1); + return leaves; +} +/** + * Inserts the tapleaves into the taproot tree. + * @param leaves The tapleaves to insert. + * @returns The taproot tree. + * @throws Throws an error if there is no room left to insert a tapleaf in the tree. + */ +function instertLeavesInTree(leaves) { + let tree; + for (const leaf of leaves) { + tree = instertLeafInTree(leaf, tree); + if (!tree) throw new Error(`No room left to insert tapleaf in tree`); + } + return tree; +} +/** + * Inserts a tapleaf into the taproot tree. + * @param leaf The tapleaf to insert. + * @param tree The taproot tree. + * @param depth The current depth. Optional. + * @returns The updated taproot tree. + */ +function instertLeafInTree(leaf, tree, depth = 0) { + if (depth > bip341_js_1.MAX_TAPTREE_DEPTH) + throw new Error('Max taptree depth exceeded.'); + if (leaf.depth === depth) { + if (!tree) + return { + output: leaf.script, + version: leaf.leafVersion, + }; + return; + } + if ((0, types_js_1.isTapleaf)(tree)) return; + const leftSide = instertLeafInTree(leaf, tree && tree[0], depth + 1); + if (leftSide) return [leftSide, tree && tree[1]]; + const rightSide = instertLeafInTree(leaf, tree && tree[1], depth + 1); + if (rightSide) return [tree && tree[0], rightSide]; +} +/** + * Checks the input fields for mixed taproot and non-taproot fields. + * @param inputData The original input data. + * @param newInputData The new input data. + * @param action The action being performed. + * @throws Throws an error if the input fields are inconsistent. + */ +function checkMixedTaprootAndNonTaprootInputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootInput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootInput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootInput(newInputData) && + hasNonTaprootFields(newInputData); // todo: bad? use !=== + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +/** + * Checks the output fields for mixed taproot and non-taproot fields. + * @param inputData The original output data. + * @param newInputData The new output data. + * @param action The action being performed. + * @throws Throws an error if the output fields are inconsistent. + */ +function checkMixedTaprootAndNonTaprootOutputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootOutput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootOutput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootOutput(newInputData) && + hasNonTaprootFields(newInputData); + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +/** + * Checks if the tap leaf is part of the tap tree for the given input data. + * Throws an error if the tap leaf is not part of the tap tree. + * @param inputData - The original PsbtInput data. + * @param newInputData - The new PsbtInput data. + * @param action - The action being performed. + * @throws {Error} - If the tap leaf is not part of the tap tree. + */ +function checkIfTapLeafInTree(inputData, newInputData, action) { + if (newInputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + const oldLeafsInTree = (inputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + if (!newLeafsInTree || !oldLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } else if (inputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, inputData.tapMerkleRoot), + ); + if (!newLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } +} +/** + * Checks if a TapLeafScript is present in a Merkle tree. + * @param tapLeaf The TapLeafScript to check. + * @param merkleRoot The Merkle root of the tree. If not provided, the function assumes the TapLeafScript is present. + * @returns A boolean indicating whether the TapLeafScript is present in the tree. + */ +function isTapLeafInTree(tapLeaf, merkleRoot) { + if (!merkleRoot) return true; + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + const rootHash = (0, bip341_js_1.rootHashFromPath)( + tapLeaf.controlBlock, + leafHash, + ); + return tools.compare(rootHash, merkleRoot) === 0; +} +/** + * Sorts the signatures in the input's tapScriptSig array based on their position in the tapLeaf script. + * + * @param input - The PsbtInput object. + * @param tapLeaf - The TapLeafScript object. + * @returns An array of sorted signatures as Buffers. + */ +function sortSignatures(input, tapLeaf) { + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return ( + (input.tapScriptSig || []) + // .filter(tss => tss.leafHash.equals(leafHash)) + .filter(tss => tools.compare(tss.leafHash, leafHash) === 0) + .map(tss => addPubkeyPositionInScript(tapLeaf.script, tss)) + .sort((t1, t2) => t2.positionInScript - t1.positionInScript) + .map(t => t.signature) + ); +} +/** + * Adds the position of a public key in a script to a TapScriptSig object. + * @param script The script in which to find the position of the public key. + * @param tss The TapScriptSig object to add the position to. + * @returns A TapScriptSigWitPosition object with the added position. + */ +function addPubkeyPositionInScript(script, tss) { + return Object.assign( + { + positionInScript: (0, psbtutils_js_1.pubkeyPositionInScript)( + tss.pubkey, + script, + ), + }, + tss, + ); +} +/** + * Find tapleaf by hash, or get the signed tapleaf with the shortest path. + */ +function findTapLeafToFinalize(input, inputIndex, leafHashToFinalize) { + if (!input.tapScriptSig || !input.tapScriptSig.length) + throw new Error( + `Can not finalize taproot input #${inputIndex}. No tapleaf script signature provided.`, + ); + const tapLeaf = (input.tapLeafScript || []) + .sort((a, b) => a.controlBlock.length - b.controlBlock.length) + .find(leaf => + canFinalizeLeaf(leaf, input.tapScriptSig, leafHashToFinalize), + ); + if (!tapLeaf) + throw new Error( + `Can not finalize taproot input #${inputIndex}. Signature for tapleaf script not found.`, + ); + return tapLeaf; +} +/** + * Determines whether a TapLeafScript can be finalized. + * + * @param leaf - The TapLeafScript to check. + * @param tapScriptSig - The array of TapScriptSig objects. + * @param hash - The optional hash to compare with the leaf hash. + * @returns A boolean indicating whether the TapLeafScript can be finalized. + */ +function canFinalizeLeaf(leaf, tapScriptSig, hash) { + const leafHash = (0, bip341_js_1.tapleafHash)({ + output: leaf.script, + version: leaf.leafVersion, + }); + const whiteListedHash = !hash || tools.compare(leafHash, hash) === 0; + return ( + whiteListedHash && + tapScriptSig.find(tss => tools.compare(tss.leafHash, leafHash) === 0) !== + undefined + ); +} +/** + * Checks if the given PsbtInput or PsbtOutput has non-taproot fields. + * Non-taproot fields include redeemScript, witnessScript, and bip32Derivation. + * @param io The PsbtInput or PsbtOutput to check. + * @returns A boolean indicating whether the given input or output has non-taproot fields. + */ +function hasNonTaprootFields(io) { + return ( + io && + !!( + io.redeemScript || + io.witnessScript || + (io.bip32Derivation && io.bip32Derivation.length) + ) + ); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.d.ts new file mode 100644 index 0000000..52e16c8 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/bip371.d.ts @@ -0,0 +1,89 @@ +import { Taptree } from '../types.js'; +import { PsbtInput, PsbtOutput, TapLeaf } from 'bip174'; +/** + * Converts a public key to an X-only public key. + * @param pubKey The public key to convert. + * @returns The X-only public key. + */ +export declare const toXOnly: (pubKey: Uint8Array) => Uint8Array; +/** + * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided. + * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path. + * @param inputIndex the position of the PSBT input. + * @param input the PSBT input. + * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash + * and will try to build the finalScriptWitness. + * @returns the finalScriptWitness or throws an exception if no tapleaf found. + */ +export declare function tapScriptFinalizer(inputIndex: number, input: PsbtInput, tapLeafHashToFinalize?: Uint8Array): { + finalScriptWitness: Uint8Array | undefined; +}; +/** + * Serializes a taproot signature. + * @param sig The signature to serialize. + * @param sighashType The sighash type. Optional. + * @returns The serialized taproot signature. + */ +export declare function serializeTaprootSignature(sig: Uint8Array, sighashType?: number): Uint8Array; +/** + * Checks if a PSBT input is a taproot input. + * @param input The PSBT input to check. + * @returns True if the input is a taproot input, false otherwise. + */ +export declare function isTaprootInput(input: PsbtInput): boolean; +/** + * Checks if a PSBT output is a taproot output. + * @param output The PSBT output to check. + * @param script The script to check. Optional. + * @returns True if the output is a taproot output, false otherwise. + */ +export declare function isTaprootOutput(output: PsbtOutput, script?: Uint8Array): boolean; +/** + * Checks the taproot input fields for consistency. + * @param inputData The original input data. + * @param newInputData The new input data. + * @param action The action being performed. + * @throws Throws an error if the input fields are inconsistent. + */ +export declare function checkTaprootInputFields(inputData: PsbtInput, newInputData: PsbtInput, action: string): void; +/** + * Checks the taproot output fields for consistency. + * @param outputData The original output data. + * @param newOutputData The new output data. + * @param action The action being performed. + * @throws Throws an error if the output fields are inconsistent. + */ +export declare function checkTaprootOutputFields(outputData: PsbtOutput, newOutputData: PsbtOutput, action: string): void; +/** + * Tweak the internal public key for a specific input. + * @param inputIndex - The index of the input. + * @param input - The PsbtInput object representing the input. + * @returns The tweaked internal public key. + * @throws Error if the tap internal key cannot be tweaked. + */ +export declare function tweakInternalPubKey(inputIndex: number, input: PsbtInput): Uint8Array; +/** + * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @param tree the binary tap tree + * @returns a list of BIP 371 tapleaves + */ +export declare function tapTreeToList(tree: Taptree): TapLeaf[]; +/** + * Convert a BIP371 TapLeaf list to a TapTree (binary). + * @param leaves a list of tapleaves where each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed + */ +export declare function tapTreeFromList(leaves?: TapLeaf[]): Taptree; +/** + * Checks the taproot input for signatures. + * @param input The PSBT input to check. + * @param action The action being performed. + * @returns True if the input has taproot signatures, false otherwise. + */ +export declare function checkTaprootInputForSigs(input: PsbtInput, action: string): boolean; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.cjs new file mode 100644 index 0000000..6918f02 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.cjs @@ -0,0 +1,228 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.isP2TR = + exports.isP2SHScript = + exports.isP2WSHScript = + exports.isP2WPKH = + exports.isP2PKH = + exports.isP2PK = + exports.isP2MS = + void 0; +exports.witnessStackToScriptWitness = witnessStackToScriptWitness; +exports.pubkeyPositionInScript = pubkeyPositionInScript; +exports.pubkeyInScript = pubkeyInScript; +exports.checkInputForSig = checkInputForSig; +exports.signatureBlocksAction = signatureBlocksAction; +const varuint = __importStar(require('varuint-bitcoin')); +const bscript = __importStar(require('../script.cjs')); +const transaction_js_1 = require('../transaction.cjs'); +const crypto_js_1 = require('../crypto.cjs'); +const payments = __importStar(require('../payments/index.cjs')); +const tools = __importStar(require('uint8array-tools')); +/** + * Checks if a given payment factory can generate a payment script from a given script. + * @param payment The payment factory to check. + * @returns A function that takes a script and returns a boolean indicating whether the payment factory can generate a payment script from the script. + */ +function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; +} +exports.isP2MS = isPaymentFactory(payments.p2ms); +exports.isP2PK = isPaymentFactory(payments.p2pk); +exports.isP2PKH = isPaymentFactory(payments.p2pkh); +exports.isP2WPKH = isPaymentFactory(payments.p2wpkh); +exports.isP2WSHScript = isPaymentFactory(payments.p2wsh); +exports.isP2SHScript = isPaymentFactory(payments.p2sh); +exports.isP2TR = isPaymentFactory(payments.p2tr); +/** + * Converts a witness stack to a script witness. + * @param witness The witness stack to convert. + * @returns The script witness as a Buffer. + */ +function witnessStackToScriptWitness(witness) { + let buffer = new Uint8Array(0); + function writeSlice(slice) { + buffer = tools.concat([buffer, slice]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = tools.concat([buffer, new Uint8Array(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; +} +/** + * Finds the position of a public key in a script. + * @param pubkey The public key to search for. + * @param script The script to search in. + * @returns The index of the public key in the script, or -1 if not found. + * @throws {Error} If there is an unknown script error. + */ +function pubkeyPositionInScript(pubkey, script) { + const pubkeyHash = (0, crypto_js_1.hash160)(pubkey); + const pubkeyXOnly = pubkey.slice(1, 33); // slice before calling? + const decompiled = bscript.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.findIndex(element => { + if (typeof element === 'number') return false; + return ( + tools.compare(pubkey, element) === 0 || + tools.compare(pubkeyHash, element) === 0 || + tools.compare(pubkeyXOnly, element) === 0 + ); + }); +} +/** + * Checks if a public key is present in a script. + * @param pubkey The public key to check. + * @param script The script to search in. + * @returns A boolean indicating whether the public key is present in the script. + */ +function pubkeyInScript(pubkey, script) { + return pubkeyPositionInScript(pubkey, script) !== -1; +} +/** + * Checks if an input contains a signature for a specific action. + * @param input - The input to check. + * @param action - The action to check for. + * @returns A boolean indicating whether the input contains a signature for the specified action. + */ +function checkInputForSig(input, action) { + const pSigs = extractPartialSigs(input); + return pSigs.some(pSig => + signatureBlocksAction(pSig, bscript.signature.decode, action), + ); +} +/** + * Determines if a given action is allowed for a signature block. + * @param signature - The signature block. + * @param signatureDecodeFn - The function used to decode the signature. + * @param action - The action to be checked. + * @returns True if the action is allowed, false otherwise. + */ +function signatureBlocksAction(signature, signatureDecodeFn, action) { + const { hashType } = signatureDecodeFn(signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_js_1.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_js_1.Transaction.SIGHASH_ALL: + break; + case transaction_js_1.Transaction.SIGHASH_SINGLE: + case transaction_js_1.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + return true; + } + return false; +} +/** + * Extracts the signatures from a PsbtInput object. + * If the input has partial signatures, it returns an array of the signatures. + * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness. + * If it does, it extracts the signatures from the final scripts and returns them. + * If none of the above conditions are met, it returns an empty array. + * + * @param input - The PsbtInput object from which to extract the signatures. + * @returns An array of signatures extracted from the PsbtInput object. + */ +function extractPartialSigs(input) { + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return []; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + return pSigs.map(p => p.signature); +} +/** + * Retrieves the partial signatures (Psigs) from the input's final scripts. + * Psigs are extracted from both the final scriptSig and final scriptWitness of the input. + * Only canonical script signatures are considered. + * + * @param input - The PsbtInput object representing the input. + * @returns An array of PartialSig objects containing the extracted Psigs. + */ +function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return ( + item instanceof Uint8Array && bscript.isCanonicalScriptSignature(item) + ); + }) + .map(sig => ({ signature: sig })); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.d.ts new file mode 100644 index 0000000..64955e0 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/psbt/psbtutils.d.ts @@ -0,0 +1,49 @@ +import { PsbtInput } from 'bip174'; +export declare const isP2MS: (script: Uint8Array) => boolean; +export declare const isP2PK: (script: Uint8Array) => boolean; +export declare const isP2PKH: (script: Uint8Array) => boolean; +export declare const isP2WPKH: (script: Uint8Array) => boolean; +export declare const isP2WSHScript: (script: Uint8Array) => boolean; +export declare const isP2SHScript: (script: Uint8Array) => boolean; +export declare const isP2TR: (script: Uint8Array) => boolean; +/** + * Converts a witness stack to a script witness. + * @param witness The witness stack to convert. + * @returns The script witness as a Buffer. + */ +export declare function witnessStackToScriptWitness(witness: Uint8Array[]): Uint8Array; +/** + * Finds the position of a public key in a script. + * @param pubkey The public key to search for. + * @param script The script to search in. + * @returns The index of the public key in the script, or -1 if not found. + * @throws {Error} If there is an unknown script error. + */ +export declare function pubkeyPositionInScript(pubkey: Uint8Array, script: Uint8Array): number; +/** + * Checks if a public key is present in a script. + * @param pubkey The public key to check. + * @param script The script to search in. + * @returns A boolean indicating whether the public key is present in the script. + */ +export declare function pubkeyInScript(pubkey: Uint8Array, script: Uint8Array): boolean; +/** + * Checks if an input contains a signature for a specific action. + * @param input - The input to check. + * @param action - The action to check for. + * @returns A boolean indicating whether the input contains a signature for the specified action. + */ +export declare function checkInputForSig(input: PsbtInput, action: string): boolean; +type SignatureDecodeFunc = (buffer: Uint8Array) => { + signature: Uint8Array; + hashType: number; +}; +/** + * Determines if a given action is allowed for a signature block. + * @param signature - The signature block. + * @param signatureDecodeFn - The function used to decode the signature. + * @param action - The action to be checked. + * @returns True if the action is allowed, false otherwise. + */ +export declare function signatureBlocksAction(signature: Uint8Array, signatureDecodeFn: SignatureDecodeFunc, action: string): boolean; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.cjs new file mode 100644 index 0000000..dd28888 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.cjs @@ -0,0 +1,133 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.encodingLength = encodingLength; +exports.encode = encode; +exports.decode = decode; +const ops_js_1 = require('./ops.cjs'); +const tools = __importStar(require('uint8array-tools')); +/** + * Calculates the encoding length of a number used for push data in Bitcoin transactions. + * @param i The number to calculate the encoding length for. + * @returns The encoding length of the number. + */ +function encodingLength(i) { + return i < ops_js_1.OPS.OP_PUSHDATA1 + ? 1 + : i <= 0xff + ? 2 + : i <= 0xffff + ? 3 + : 5; +} +/** + * Encodes a number into a buffer using a variable-length encoding scheme. + * The encoded buffer is written starting at the specified offset. + * Returns the size of the encoded buffer. + * + * @param buffer - The buffer to write the encoded data into. + * @param num - The number to encode. + * @param offset - The offset at which to start writing the encoded buffer. + * @returns The size of the encoded buffer. + */ +function encode(buffer, num, offset) { + const size = encodingLength(num); + // ~6 bit + if (size === 1) { + tools.writeUInt8(buffer, offset, num); + // 8 bit + } else if (size === 2) { + tools.writeUInt8(buffer, offset, ops_js_1.OPS.OP_PUSHDATA1); + tools.writeUInt8(buffer, offset + 1, num); + // 16 bit + } else if (size === 3) { + tools.writeUInt8(buffer, offset, ops_js_1.OPS.OP_PUSHDATA2); + tools.writeUInt16(buffer, offset + 1, num, 'LE'); + // 32 bit + } else { + tools.writeUInt8(buffer, offset, ops_js_1.OPS.OP_PUSHDATA4); + tools.writeUInt32(buffer, offset + 1, num, 'LE'); + } + return size; +} +/** + * Decodes a buffer and returns information about the opcode, number, and size. + * @param buffer - The buffer to decode. + * @param offset - The offset within the buffer to start decoding. + * @returns An object containing the opcode, number, and size, or null if decoding fails. + */ +function decode(buffer, offset) { + const opcode = tools.readUInt8(buffer, offset); + let num; + let size; + // ~6 bit + if (opcode < ops_js_1.OPS.OP_PUSHDATA1) { + num = opcode; + size = 1; + // 8 bit + } else if (opcode === ops_js_1.OPS.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null; + num = tools.readUInt8(buffer, offset + 1); + size = 2; + // 16 bit + } else if (opcode === ops_js_1.OPS.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null; + num = tools.readUInt16(buffer, offset + 1, 'LE'); + size = 3; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null; + if (opcode !== ops_js_1.OPS.OP_PUSHDATA4) + throw new Error('Unexpected opcode'); + num = tools.readUInt32(buffer, offset + 1, 'LE'); + size = 5; + } + return { + opcode, + number: num, + size, + }; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.d.ts new file mode 100644 index 0000000..2ce9109 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/push_data.d.ts @@ -0,0 +1,28 @@ +/** + * Calculates the encoding length of a number used for push data in Bitcoin transactions. + * @param i The number to calculate the encoding length for. + * @returns The encoding length of the number. + */ +export declare function encodingLength(i: number): number; +/** + * Encodes a number into a buffer using a variable-length encoding scheme. + * The encoded buffer is written starting at the specified offset. + * Returns the size of the encoded buffer. + * + * @param buffer - The buffer to write the encoded data into. + * @param num - The number to encode. + * @param offset - The offset at which to start writing the encoded buffer. + * @returns The size of the encoded buffer. + */ +export declare function encode(buffer: Uint8Array, num: number, offset: number): number; +/** + * Decodes a buffer and returns information about the opcode, number, and size. + * @param buffer - The buffer to decode. + * @param offset - The offset within the buffer to start decoding. + * @returns An object containing the opcode, number, and size, or null if decoding fails. + */ +export declare function decode(buffer: Uint8Array, offset: number): { + opcode: number; + number: number; + size: number; +} | null; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.cjs new file mode 100644 index 0000000..0af216d --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.cjs @@ -0,0 +1,261 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.signature = exports.number = exports.OPS = void 0; +exports.isPushOnly = isPushOnly; +exports.countNonPushOnlyOPs = countNonPushOnlyOPs; +exports.compile = compile; +exports.decompile = decompile; +exports.toASM = toASM; +exports.fromASM = fromASM; +exports.toStack = toStack; +exports.isCanonicalPubKey = isCanonicalPubKey; +exports.isDefinedHashType = isDefinedHashType; +exports.isCanonicalScriptSignature = isCanonicalScriptSignature; +/** + * Script tools, including decompile, compile, toASM, fromASM, toStack, isCanonicalPubKey, isCanonicalScriptSignature + * @packageDocumentation + */ +const bip66 = __importStar(require('./bip66.cjs')); +const ops_js_1 = require('./ops.cjs'); +Object.defineProperty(exports, 'OPS', { + enumerable: true, + get: function () { + return ops_js_1.OPS; + }, +}); +const pushdata = __importStar(require('./push_data.cjs')); +const scriptNumber = __importStar(require('./script_number.cjs')); +const scriptSignature = __importStar(require('./script_signature.cjs')); +const types = __importStar(require('./types.cjs')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const OP_INT_BASE = ops_js_1.OPS.OP_RESERVED; // OP_1 - 1 +const StackSchema = v.array(v.union([v.instance(Uint8Array), v.number()])); +function isOPInt(value) { + return ( + v.is(v.number(), value) && + (value === ops_js_1.OPS.OP_0 || + (value >= ops_js_1.OPS.OP_1 && value <= ops_js_1.OPS.OP_16) || + value === ops_js_1.OPS.OP_1NEGATE) + ); +} +function isPushOnlyChunk(value) { + return v.is(types.BufferSchema, value) || isOPInt(value); +} +function isPushOnly(value) { + return v.is(v.pipe(v.any(), v.everyItem(isPushOnlyChunk)), value); +} +function countNonPushOnlyOPs(value) { + return value.length - value.filter(isPushOnlyChunk).length; +} +function asMinimalOP(buffer) { + if (buffer.length === 0) return ops_js_1.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return ops_js_1.OPS.OP_1NEGATE; +} +function chunksIsBuffer(buf) { + return buf instanceof Uint8Array; +} +function chunksIsArray(buf) { + return v.is(StackSchema, buf); +} +function singleChunkIsBuffer(buf) { + return buf instanceof Uint8Array; +} +/** + * Compiles an array of chunks into a Buffer. + * + * @param chunks - The array of chunks to compile. + * @returns The compiled Buffer. + * @throws Error if the compilation fails. + */ +function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + v.parse(StackSchema, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = new Uint8Array(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + tools.writeUInt8(buffer, offset, opcode); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + buffer.set(chunk, offset); + offset += chunk.length; + // opcode + } else { + tools.writeUInt8(buffer, offset, chunk); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; +} +function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + v.parse(types.BufferSchema, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > ops_js_1.OPS.OP_0 && opcode <= ops_js_1.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; +} +/** + * Converts the given chunks into an ASM (Assembly) string representation. + * If the chunks parameter is a Buffer, it will be decompiled into a Stack before conversion. + * @param chunks - The chunks to convert into ASM. + * @returns The ASM string representation of the chunks. + */ +function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + if (!chunks) { + throw new Error('Could not convert invalid chunks to ASM'); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return tools.toHex(chunk); + chunk = op; + } + // opcode! + return ops_js_1.REVERSE_OPS[chunk]; + }) + .join(' '); +} +/** + * Converts an ASM string to a Buffer. + * @param asm The ASM string to convert. + * @returns The converted Buffer. + */ +function fromASM(asm) { + v.parse(v.string(), asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (ops_js_1.OPS[chunkStr] !== undefined) return ops_js_1.OPS[chunkStr]; + v.parse(types.HexSchema, chunkStr); + // data! + return tools.fromHex(chunkStr); + }), + ); +} +/** + * Converts the given chunks into a stack of buffers. + * + * @param chunks - The chunks to convert. + * @returns The stack of buffers. + */ +function toStack(chunks) { + chunks = decompile(chunks); + v.parse(v.custom(isPushOnly), chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === ops_js_1.OPS.OP_0) return new Uint8Array(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); +} +function isCanonicalPubKey(buffer) { + return types.isPoint(buffer); +} +function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + return hashTypeMod > 0x00 && hashTypeMod < 0x04; +} +function isCanonicalScriptSignature(buffer) { + if (!(buffer instanceof Uint8Array)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); +} +exports.number = scriptNumber; +exports.signature = scriptSignature; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.d.ts new file mode 100644 index 0000000..9d31f50 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script.d.ts @@ -0,0 +1,41 @@ +import { OPS } from './ops.js'; +import { Stack } from './payments/index.js'; +import * as scriptNumber from './script_number.js'; +import * as scriptSignature from './script_signature.js'; +export { OPS }; +export declare function isPushOnly(value: Stack): boolean; +export declare function countNonPushOnlyOPs(value: Stack): number; +/** + * Compiles an array of chunks into a Buffer. + * + * @param chunks - The array of chunks to compile. + * @returns The compiled Buffer. + * @throws Error if the compilation fails. + */ +export declare function compile(chunks: Uint8Array | Stack): Uint8Array; +export declare function decompile(buffer: Uint8Array | Array): Array | null; +/** + * Converts the given chunks into an ASM (Assembly) string representation. + * If the chunks parameter is a Buffer, it will be decompiled into a Stack before conversion. + * @param chunks - The chunks to convert into ASM. + * @returns The ASM string representation of the chunks. + */ +export declare function toASM(chunks: Uint8Array | Array): string; +/** + * Converts an ASM string to a Buffer. + * @param asm The ASM string to convert. + * @returns The converted Buffer. + */ +export declare function fromASM(asm: string): Uint8Array; +/** + * Converts the given chunks into a stack of buffers. + * + * @param chunks - The chunks to convert. + * @returns The stack of buffers. + */ +export declare function toStack(chunks: Uint8Array | Array): Uint8Array[]; +export declare function isCanonicalPubKey(buffer: Uint8Array): boolean; +export declare function isDefinedHashType(hashType: number): boolean; +export declare function isCanonicalScriptSignature(buffer: Uint8Array): boolean; +export declare const number: typeof scriptNumber; +export declare const signature: typeof scriptSignature; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.cjs new file mode 100644 index 0000000..1ef0334 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.cjs @@ -0,0 +1,122 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.decode = decode; +exports.encode = encode; +const tools = __importStar(require('uint8array-tools')); +/** + * Decodes a script number from a buffer. + * + * @param buffer - The buffer containing the script number. + * @param maxLength - The maximum length of the script number. Defaults to 4. + * @param minimal - Whether the script number should be minimal. Defaults to true. + * @returns The decoded script number. + * @throws {TypeError} If the script number overflows the maximum length. + * @throws {Error} If the script number is not minimally encoded when minimal is true. + */ +function decode(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = tools.readUInt32(buffer, 0, 'LE'); + const b = tools.readUInt8(buffer, 4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; +} +function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; +} +/** + * Encodes a number into a Uint8Array using a specific format. + * + * @param _number - The number to encode. + * @returns The encoded number as a Uint8Array. + */ +function encode(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = new Uint8Array(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + tools.writeUInt8(buffer, i, value & 0xff); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + tools.writeUInt8(buffer, size - 1, negative ? 0x80 : 0x00); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.d.ts new file mode 100644 index 0000000..26a2ea0 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_number.d.ts @@ -0,0 +1,18 @@ +/** + * Decodes a script number from a buffer. + * + * @param buffer - The buffer containing the script number. + * @param maxLength - The maximum length of the script number. Defaults to 4. + * @param minimal - Whether the script number should be minimal. Defaults to true. + * @returns The decoded script number. + * @throws {TypeError} If the script number overflows the maximum length. + * @throws {Error} If the script number is not minimally encoded when minimal is true. + */ +export declare function decode(buffer: Uint8Array, maxLength?: number, minimal?: boolean): number; +/** + * Encodes a number into a Uint8Array using a specific format. + * + * @param _number - The number to encode. + * @returns The encoded number as a Uint8Array. + */ +export declare function encode(_number: number): Uint8Array; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.cjs new file mode 100644 index 0000000..0ef4ee8 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.cjs @@ -0,0 +1,123 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.decode = decode; +exports.encode = encode; +const bip66 = __importStar(require('./bip66.cjs')); +const script_js_1 = require('./script.cjs'); +const v = __importStar(require('valibot')); +const tools = __importStar(require('uint8array-tools')); +const types_js_1 = require('./types.cjs'); +const ZERO = new Uint8Array(1); +/** + * Converts a buffer to a DER-encoded buffer. + * @param x - The buffer to be converted. + * @returns The DER-encoded buffer. + */ +function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO; + x = x.slice(i); + if (x[0] & 0x80) return tools.concat([ZERO, x]); + return x; +} +/** + * Converts a DER-encoded signature to a buffer. + * If the first byte of the input buffer is 0x00, it is skipped. + * The resulting buffer is 32 bytes long, filled with zeros if necessary. + * @param x - The DER-encoded signature. + * @returns The converted buffer. + */ +function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = new Uint8Array(32); + const bstart = Math.max(0, 32 - x.length); + buffer.set(x, bstart); + return buffer; +} +// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) +/** + * Decodes a buffer into a ScriptSignature object. + * @param buffer - The buffer to decode. + * @returns The decoded ScriptSignature object. + * @throws Error if the hashType is invalid. + */ +function decode(buffer) { + const hashType = tools.readUInt8(buffer, buffer.length - 1); + if (!(0, script_js_1.isDefinedHashType)(hashType)) { + throw new Error('Invalid hashType ' + hashType); + } + const decoded = bip66.decode(buffer.subarray(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = tools.concat([r, s]); + return { signature, hashType }; +} +/** + * Encodes a signature and hash type into a buffer. + * @param signature - The signature to encode. + * @param hashType - The hash type to encode. + * @returns The encoded buffer. + * @throws Error if the hashType is invalid. + */ +function encode(signature, hashType) { + v.parse( + v.object({ + signature: (0, types_js_1.NBufferSchemaFactory)(64), + hashType: types_js_1.UInt8Schema, + }), + { signature, hashType }, + ); + if (!(0, script_js_1.isDefinedHashType)(hashType)) { + throw new Error('Invalid hashType ' + hashType); + } + const hashTypeBuffer = new Uint8Array(1); + tools.writeUInt8(hashTypeBuffer, 0, hashType); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return tools.concat([bip66.encode(r, s), hashTypeBuffer]); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.d.ts new file mode 100644 index 0000000..16f6458 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/script_signature.d.ts @@ -0,0 +1,20 @@ +interface ScriptSignature { + signature: Uint8Array; + hashType: number; +} +/** + * Decodes a buffer into a ScriptSignature object. + * @param buffer - The buffer to decode. + * @returns The decoded ScriptSignature object. + * @throws Error if the hashType is invalid. + */ +export declare function decode(buffer: Uint8Array): ScriptSignature; +/** + * Encodes a signature and hash type into a buffer. + * @param signature - The signature to encode. + * @param hashType - The hash type to encode. + * @returns The encoded buffer. + * @throws Error if the hashType is invalid. + */ +export declare function encode(signature: Uint8Array, hashType: number): Uint8Array; +export {}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.cjs new file mode 100644 index 0000000..f05cf7f --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.cjs @@ -0,0 +1,602 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Transaction = void 0; +const bufferutils_js_1 = require('./bufferutils.cjs'); +const bcrypto = __importStar(require('./crypto.cjs')); +const sha256_1 = require('@noble/hashes/sha256'); +const bscript = __importStar(require('./script.cjs')); +const script_js_1 = require('./script.cjs'); +const types = __importStar(require('./types.cjs')); +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +function varSliceSize(someScript) { + const length = someScript.length; + return bufferutils_js_1.varuint.encodingLength(length) + length; +} +function vectorSize(someVector) { + const length = someVector.length; + return ( + bufferutils_js_1.varuint.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); +} +const EMPTY_BUFFER = new Uint8Array(0); +const EMPTY_WITNESS = []; +const ZERO = tools.fromHex( + '0000000000000000000000000000000000000000000000000000000000000000', +); +const ONE = tools.fromHex( + '0000000000000000000000000000000000000000000000000000000000000001', +); +const VALUE_UINT64_MAX = tools.fromHex('ffffffffffffffff'); +const BLANK_OUTPUT = { + script: EMPTY_BUFFER, + valueBuffer: VALUE_UINT64_MAX, +}; +function isOutput(out) { + return out.value !== undefined; +} +/** + * Represents a Bitcoin transaction. + */ +class Transaction { + static DEFAULT_SEQUENCE = 0xffffffff; + static SIGHASH_DEFAULT = 0x00; + static SIGHASH_ALL = 0x01; + static SIGHASH_NONE = 0x02; + static SIGHASH_SINGLE = 0x03; + static SIGHASH_ANYONECANPAY = 0x80; + static SIGHASH_OUTPUT_MASK = 0x03; + static SIGHASH_INPUT_MASK = 0x80; + static ADVANCED_TRANSACTION_MARKER = 0x00; + static ADVANCED_TRANSACTION_FLAG = 0x01; + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_js_1.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(tools.fromHex(hex), false); + } + static isCoinbaseHash(buffer) { + v.parse(types.Hash256bitSchema, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + version = 1; + locktime = 0; + ins = []; + outs = []; + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + v.parse( + v.tuple([ + types.Hash256bitSchema, + types.UInt32Schema, + v.nullable(v.optional(types.UInt32Schema)), + v.nullable(v.optional(types.BufferSchema)), + ]), + [hash, index, sequence, scriptSig], + ); + if (sequence === undefined || sequence === null) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_BUFFER, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + v.parse(v.tuple([types.BufferSchema, types.SatoshiSchema]), [ + scriptPubKey, + value, + ]); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + bufferutils_js_1.varuint.encodingLength(this.ins.length) + + bufferutils_js_1.varuint.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + v.parse(v.tuple([types.UInt32Schema, types.BufferSchema, v.number()]), [ + inIndex, + prevOutScript, + hashType, + ]); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript.compile( + bscript.decompile(prevOutScript).filter(x => { + return x !== script_js_1.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_BUFFER; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = new Uint8Array(txTmp.byteLength(false) + 4); + tools.writeInt32(buffer, buffer.length - 4, hashType, 'LE'); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto.hash256(buffer); + } + hashForWitnessV1(inIndex, prevOutScripts, values, hashType, leafHash, annex) { + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#common-signature-message + v.parse( + v.tuple([ + types.UInt32Schema, + v.array(types.BufferSchema), + v.array(types.SatoshiSchema), + types.UInt32Schema, + ]), + [inIndex, prevOutScripts, values, hashType], + ); + if ( + values.length !== this.ins.length || + prevOutScripts.length !== this.ins.length + ) { + throw new Error('Must supply prevout script and value for all inputs'); + } + const outputType = + hashType === Transaction.SIGHASH_DEFAULT + ? Transaction.SIGHASH_ALL + : hashType & Transaction.SIGHASH_OUTPUT_MASK; + const inputType = hashType & Transaction.SIGHASH_INPUT_MASK; + const isAnyoneCanPay = inputType === Transaction.SIGHASH_ANYONECANPAY; + const isNone = outputType === Transaction.SIGHASH_NONE; + const isSingle = outputType === Transaction.SIGHASH_SINGLE; + let hashPrevouts = EMPTY_BUFFER; + let hashAmounts = EMPTY_BUFFER; + let hashScriptPubKeys = EMPTY_BUFFER; + let hashSequences = EMPTY_BUFFER; + let hashOutputs = EMPTY_BUFFER; + if (!isAnyoneCanPay) { + let bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + 36 * this.ins.length, + ); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = (0, sha256_1.sha256)(bufferWriter.end()); + bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + 8 * this.ins.length, + ); + values.forEach(value => bufferWriter.writeInt64(value)); + hashAmounts = (0, sha256_1.sha256)(bufferWriter.end()); + bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), + ); + prevOutScripts.forEach(prevOutScript => + bufferWriter.writeVarSlice(prevOutScript), + ); + hashScriptPubKeys = (0, sha256_1.sha256)(bufferWriter.end()); + bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + 4 * this.ins.length, + ); + this.ins.forEach(txIn => bufferWriter.writeUInt32(txIn.sequence)); + hashSequences = (0, sha256_1.sha256)(bufferWriter.end()); + } + if (!(isNone || isSingle)) { + if (!this.outs.length) + throw new Error('Add outputs to the transaction before signing.'); + const txOutsSize = this.outs + .map(output => 8 + varSliceSize(output.script)) + .reduce((a, b) => a + b); + const bufferWriter = + bufferutils_js_1.BufferWriter.withCapacity(txOutsSize); + this.outs.forEach(out => { + bufferWriter.writeInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = (0, sha256_1.sha256)(bufferWriter.end()); + } else if (isSingle && inIndex < this.outs.length) { + const output = this.outs[inIndex]; + const bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + 8 + varSliceSize(output.script), + ); + bufferWriter.writeInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = (0, sha256_1.sha256)(bufferWriter.end()); + } + const spendType = (leafHash ? 2 : 0) + (annex ? 1 : 0); + // Length calculation from: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-14 + // With extension from: + // https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#signature-validation + const sigMsgSize = + 174 - + (isAnyoneCanPay ? 49 : 0) - + (isNone ? 32 : 0) + + (annex ? 32 : 0) + + (leafHash ? 37 : 0); + const sigMsgWriter = bufferutils_js_1.BufferWriter.withCapacity(sigMsgSize); + sigMsgWriter.writeUInt8(hashType); + // Transaction + sigMsgWriter.writeInt32(this.version); + sigMsgWriter.writeUInt32(this.locktime); + sigMsgWriter.writeSlice(hashPrevouts); + sigMsgWriter.writeSlice(hashAmounts); + sigMsgWriter.writeSlice(hashScriptPubKeys); + sigMsgWriter.writeSlice(hashSequences); + if (!(isNone || isSingle)) { + sigMsgWriter.writeSlice(hashOutputs); + } + // Input + sigMsgWriter.writeUInt8(spendType); + if (isAnyoneCanPay) { + const input = this.ins[inIndex]; + sigMsgWriter.writeSlice(input.hash); + sigMsgWriter.writeUInt32(input.index); + sigMsgWriter.writeInt64(values[inIndex]); + sigMsgWriter.writeVarSlice(prevOutScripts[inIndex]); + sigMsgWriter.writeUInt32(input.sequence); + } else { + sigMsgWriter.writeUInt32(inIndex); + } + if (annex) { + const bufferWriter = bufferutils_js_1.BufferWriter.withCapacity( + varSliceSize(annex), + ); + bufferWriter.writeVarSlice(annex); + sigMsgWriter.writeSlice((0, sha256_1.sha256)(bufferWriter.end())); + } + // Output + if (isSingle) { + sigMsgWriter.writeSlice(hashOutputs); + } + // BIP342 extension + if (leafHash) { + sigMsgWriter.writeSlice(leafHash); + sigMsgWriter.writeUInt8(0); + sigMsgWriter.writeUInt32(0xffffffff); + } + // Extra zero byte because: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-19 + return bcrypto.taggedHash( + 'TapSighash', + tools.concat([Uint8Array.from([0x00]), sigMsgWriter.end()]), + ); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + v.parse( + v.tuple([ + types.UInt32Schema, + types.BufferSchema, + types.SatoshiSchema, + types.UInt32Schema, + ]), + [inIndex, prevOutScript, value, hashType], + ); + let tbuffer = Uint8Array.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = new Uint8Array(36 * this.ins.length); + bufferWriter = new bufferutils_js_1.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = new Uint8Array(4 * this.ins.length); + bufferWriter = new bufferutils_js_1.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = new Uint8Array(txOutsSize); + bufferWriter = new bufferutils_js_1.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = new Uint8Array(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_js_1.BufferWriter(tbuffer, 0); + bufferWriter.writeInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto.hash256(tbuffer); + } + tbuffer = new Uint8Array(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_js_1.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return new Uint8Array(32); + return bcrypto.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return tools.toHex( + (0, bufferutils_js_1.reverseBuffer)(this.getHash(false)), + ); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return tools.toHex(this.toBuffer(undefined, undefined)); + } + setInputScript(index, scriptSig) { + v.parse(v.tuple([v.number(), types.BufferSchema]), [index, scriptSig]); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + v.parse(v.tuple([v.number(), v.array(types.BufferSchema)]), [ + index, + witness, + ]); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = new Uint8Array(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_js_1.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } +} +exports.Transaction = Transaction; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.d.ts new file mode 100644 index 0000000..6f9d615 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/transaction.d.ts @@ -0,0 +1,59 @@ +export interface Output { + script: Uint8Array; + value: bigint; +} +export interface Input { + hash: Uint8Array; + index: number; + script: Uint8Array; + sequence: number; + witness: Uint8Array[]; +} +/** + * Represents a Bitcoin transaction. + */ +export declare class Transaction { + static readonly DEFAULT_SEQUENCE = 4294967295; + static readonly SIGHASH_DEFAULT = 0; + static readonly SIGHASH_ALL = 1; + static readonly SIGHASH_NONE = 2; + static readonly SIGHASH_SINGLE = 3; + static readonly SIGHASH_ANYONECANPAY = 128; + static readonly SIGHASH_OUTPUT_MASK = 3; + static readonly SIGHASH_INPUT_MASK = 128; + static readonly ADVANCED_TRANSACTION_MARKER = 0; + static readonly ADVANCED_TRANSACTION_FLAG = 1; + static fromBuffer(buffer: Uint8Array, _NO_STRICT?: boolean): Transaction; + static fromHex(hex: string): Transaction; + static isCoinbaseHash(buffer: Uint8Array): boolean; + version: number; + locktime: number; + ins: Input[]; + outs: Output[]; + isCoinbase(): boolean; + addInput(hash: Uint8Array, index: number, sequence?: number, scriptSig?: Uint8Array): number; + addOutput(scriptPubKey: Uint8Array, value: bigint): number; + hasWitnesses(): boolean; + weight(): number; + virtualSize(): number; + byteLength(_ALLOW_WITNESS?: boolean): number; + clone(): Transaction; + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex: number, prevOutScript: Uint8Array, hashType: number): Uint8Array; + hashForWitnessV1(inIndex: number, prevOutScripts: Uint8Array[], values: bigint[], hashType: number, leafHash?: Uint8Array, annex?: Uint8Array): Uint8Array; + hashForWitnessV0(inIndex: number, prevOutScript: Uint8Array, value: bigint, hashType: number): Uint8Array; + getHash(forWitness?: boolean): Uint8Array; + getId(): string; + toBuffer(buffer?: Uint8Array, initialOffset?: number): Uint8Array; + toHex(): string; + setInputScript(index: number, scriptSig: Uint8Array): void; + setWitness(index: number, witness: Uint8Array[]): void; + private __toBuffer; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.cjs b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.cjs new file mode 100644 index 0000000..0d57948 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.cjs @@ -0,0 +1,147 @@ +'use strict'; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.NullablePartial = + exports.SatoshiSchema = + exports.UInt32Schema = + exports.UInt8Schema = + exports.HexSchema = + exports.BufferSchema = + exports.Hash256bitSchema = + exports.Hash160bitSchema = + exports.Buffer256bitSchema = + exports.TAPLEAF_VERSION_MASK = + exports.NBufferSchemaFactory = + void 0; +exports.stacksEqual = stacksEqual; +exports.isPoint = isPoint; +exports.isTapleaf = isTapleaf; +exports.isTaptree = isTaptree; +const tools = __importStar(require('uint8array-tools')); +const v = __importStar(require('valibot')); +const ZERO32 = new Uint8Array(32); +const EC_P = tools.fromHex( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', +); +const NBufferSchemaFactory = size => + v.pipe(v.instance(Uint8Array), v.length(size)); +exports.NBufferSchemaFactory = NBufferSchemaFactory; +/** + * Checks if two arrays of Buffers are equal. + * @param a - The first array of Buffers. + * @param b - The second array of Buffers. + * @returns True if the arrays are equal, false otherwise. + */ +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return tools.compare(x, b[i]) === 0; + }); +} +/** + * Checks if the given value is a valid elliptic curve point. + * @param p - The value to check. + * @returns True if the value is a valid elliptic curve point, false otherwise. + */ +function isPoint(p) { + if (!(p instanceof Uint8Array)) return false; + if (p.length < 33) return false; + const t = p[0]; + const x = p.slice(1, 33); + if (tools.compare(ZERO32, x) === 0) return false; + if (tools.compare(x, EC_P) >= 0) return false; + if ((t === 0x02 || t === 0x03) && p.length === 33) { + return true; + } + const y = p.slice(33); + if (tools.compare(ZERO32, y) === 0) return false; + if (tools.compare(y, EC_P) >= 0) return false; + if (t === 0x04 && p.length === 65) return true; + return false; +} +exports.TAPLEAF_VERSION_MASK = 0xfe; +function isTapleaf(o) { + if (!o || !('output' in o)) return false; + if (!(o.output instanceof Uint8Array)) return false; + if (o.version !== undefined) + return (o.version & exports.TAPLEAF_VERSION_MASK) === o.version; + return true; +} +function isTaptree(scriptTree) { + if (!Array.isArray(scriptTree)) return isTapleaf(scriptTree); + if (scriptTree.length !== 2) return false; + return scriptTree.every(t => isTaptree(t)); +} +exports.Buffer256bitSchema = (0, exports.NBufferSchemaFactory)(32); +exports.Hash160bitSchema = (0, exports.NBufferSchemaFactory)(20); +exports.Hash256bitSchema = (0, exports.NBufferSchemaFactory)(32); +exports.BufferSchema = v.instance(Uint8Array); +exports.HexSchema = v.pipe(v.string(), v.regex(/^([0-9a-f]{2})+$/i)); +exports.UInt8Schema = v.pipe( + v.number(), + v.integer(), + v.minValue(0), + v.maxValue(0xff), +); +exports.UInt32Schema = v.pipe( + v.number(), + v.integer(), + v.minValue(0), + v.maxValue(0xffffffff), +); +exports.SatoshiSchema = v.pipe( + v.bigint(), + v.minValue(0n), + v.maxValue(0x7fffffffffffffffn), +); +const NullablePartial = a => + v.object( + Object.entries(a).reduce( + (acc, next) => ({ ...acc, [next[0]]: v.nullish(next[1]) }), + {}, + ), + ); +exports.NullablePartial = NullablePartial; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.d.ts b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.d.ts new file mode 100644 index 0000000..7abcd67 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/cjs/types.d.ts @@ -0,0 +1,45 @@ +import * as v from 'valibot'; +export declare const NBufferSchemaFactory: (size: number) => v.SchemaWithPipe<[v.InstanceSchema, v.LengthAction]>; +/** + * Checks if two arrays of Buffers are equal. + * @param a - The first array of Buffers. + * @param b - The second array of Buffers. + * @returns True if the arrays are equal, false otherwise. + */ +export declare function stacksEqual(a: Uint8Array[], b: Uint8Array[]): boolean; +/** + * Checks if the given value is a valid elliptic curve point. + * @param p - The value to check. + * @returns True if the value is a valid elliptic curve point, false otherwise. + */ +export declare function isPoint(p: Uint8Array | number | undefined | null): boolean; +export interface XOnlyPointAddTweakResult { + parity: 1 | 0; + xOnlyPubkey: Uint8Array; +} +export interface Tapleaf { + output: Uint8Array; + version?: number; +} +export declare const TAPLEAF_VERSION_MASK = 254; +export declare function isTapleaf(o: any): o is Tapleaf; +/** + * Binary tree repsenting script path spends for a Taproot input. + * Each node is either a single Tapleaf, or a pair of Tapleaf | Taptree. + * The tree has no balancing requirements. + */ +export type Taptree = [Taptree | Tapleaf, Taptree | Tapleaf] | Tapleaf; +export declare function isTaptree(scriptTree: any): scriptTree is Taptree; +export interface TinySecp256k1Interface { + isXOnlyPoint(p: Uint8Array): boolean; + xOnlyPointAddTweak(p: Uint8Array, tweak: Uint8Array): XOnlyPointAddTweakResult | null; +} +export declare const Buffer256bitSchema: v.SchemaWithPipe<[v.InstanceSchema, v.LengthAction]>; +export declare const Hash160bitSchema: v.SchemaWithPipe<[v.InstanceSchema, v.LengthAction]>; +export declare const Hash256bitSchema: v.SchemaWithPipe<[v.InstanceSchema, v.LengthAction]>; +export declare const BufferSchema: v.InstanceSchema; +export declare const HexSchema: v.SchemaWithPipe<[v.StringSchema, v.RegexAction]>; +export declare const UInt8Schema: v.SchemaWithPipe<[v.NumberSchema, v.IntegerAction, v.MinValueAction, v.MaxValueAction]>; +export declare const UInt32Schema: v.SchemaWithPipe<[v.NumberSchema, v.IntegerAction, v.MinValueAction, v.MaxValueAction]>; +export declare const SatoshiSchema: v.SchemaWithPipe<[v.BigintSchema, v.MinValueAction, v.MaxValueAction]>; +export declare const NullablePartial: (a: Record) => v.ObjectSchema<{}, undefined>; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/address.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/address.js new file mode 100644 index 0000000..f962414 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/address.js @@ -0,0 +1,193 @@ +import * as networks from './networks.js'; +import * as payments from './payments/index.js'; +import * as bscript from './script.js'; +import { Hash160bitSchema, UInt8Schema } from './types.js'; +import { bech32, bech32m } from 'bech32'; +import bs58check from 'bs58check'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const FUTURE_SEGWIT_MAX_SIZE = 40; +const FUTURE_SEGWIT_MIN_SIZE = 2; +const FUTURE_SEGWIT_MAX_VERSION = 16; +const FUTURE_SEGWIT_MIN_VERSION = 2; +const FUTURE_SEGWIT_VERSION_DIFF = 0x50; +const FUTURE_SEGWIT_VERSION_WARNING = + 'WARNING: Sending to a future segwit version address can lead to loss of funds. ' + + 'End users MUST be warned carefully in the GUI and asked if they wish to proceed ' + + 'with caution. Wallets should verify the segwit version from the output of fromBech32, ' + + 'then decide when it is safe to use which version of segwit.'; +/** + * Converts an output buffer to a future segwit address. + * @param output - The output buffer. + * @param network - The network object. + * @returns The future segwit address. + * @throws {TypeError} If the program length or version is invalid for segwit address. + */ +function _toFutureSegwitAddress(output, network) { + const data = output.slice(2); + if ( + data.length < FUTURE_SEGWIT_MIN_SIZE || + data.length > FUTURE_SEGWIT_MAX_SIZE + ) + throw new TypeError('Invalid program length for segwit address'); + const version = output[0] - FUTURE_SEGWIT_VERSION_DIFF; + if ( + version < FUTURE_SEGWIT_MIN_VERSION || + version > FUTURE_SEGWIT_MAX_VERSION + ) + throw new TypeError('Invalid version for segwit address'); + if (output[1] !== data.length) + throw new TypeError('Invalid script for segwit address'); + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return toBech32(data, version, network.bech32); +} +/** + * Decodes a base58check encoded Bitcoin address and returns the version and hash. + * + * @param address - The base58check encoded Bitcoin address to decode. + * @returns An object containing the version and hash of the decoded address. + * @throws {TypeError} If the address is too short or too long. + */ +export function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; +} +/** + * Converts a Bech32 or Bech32m encoded address to its corresponding data representation. + * @param address - The Bech32 or Bech32m encoded address. + * @returns An object containing the version, prefix, and data of the address. + * @throws {TypeError} If the address uses the wrong encoding. + */ +export function fromBech32(address) { + let result; + let version; + try { + result = bech32.decode(address); + } catch (e) {} + if (result) { + version = result.words[0]; + if (version !== 0) throw new TypeError(address + ' uses wrong encoding'); + } else { + result = bech32m.decode(address); + version = result.words[0]; + if (version === 0) throw new TypeError(address + ' uses wrong encoding'); + } + const data = bech32.fromWords(result.words.slice(1)); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; +} +/** + * Converts a hash to a Base58Check-encoded string. + * @param hash - The hash to be encoded. + * @param version - The version byte to be prepended to the encoded string. + * @returns The Base58Check-encoded string. + */ +export function toBase58Check(hash, version) { + v.parse(v.tuple([Hash160bitSchema, UInt8Schema]), [hash, version]); + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, version); + payload.set(hash, 1); + return bs58check.encode(payload); +} +/** + * Converts a buffer to a Bech32 or Bech32m encoded string. + * @param data - The buffer to be encoded. + * @param version - The version number to be used in the encoding. + * @param prefix - The prefix string to be used in the encoding. + * @returns The Bech32 or Bech32m encoded string. + */ +export function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return version === 0 + ? bech32.encode(prefix, words) + : bech32m.encode(prefix, words); +} +/** + * Converts an output script to a Bitcoin address. + * @param output - The output script as a Buffer. + * @param network - The Bitcoin network (optional). + * @returns The Bitcoin address corresponding to the output script. + * @throws If the output script has no matching address. + */ +export function fromOutputScript(output, network) { + // TODO: Network + network = network || networks.bitcoin; + try { + return payments.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wsh({ output, network }).address; + } catch (e) {} + try { + return payments.p2tr({ output, network }).address; + } catch (e) {} + try { + return _toFutureSegwitAddress(output, network); + } catch (e) {} + throw new Error(bscript.toASM(output) + ' has no matching Address'); +} +/** + * Converts a Bitcoin address to its corresponding output script. + * @param address - The Bitcoin address to convert. + * @param network - The Bitcoin network to use. Defaults to the Bitcoin network. + * @returns The corresponding output script as a Buffer. + * @throws If the address has an invalid prefix or no matching script. + */ +export function toOutputScript(address, network) { + network = network || networks.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments.p2wsh({ hash: decodeBech32.data }).output; + } else if (decodeBech32.version === 1) { + if (decodeBech32.data.length === 32) + return payments.p2tr({ pubkey: decodeBech32.data }).output; + } else if ( + decodeBech32.version >= FUTURE_SEGWIT_MIN_VERSION && + decodeBech32.version <= FUTURE_SEGWIT_MAX_VERSION && + decodeBech32.data.length >= FUTURE_SEGWIT_MIN_SIZE && + decodeBech32.data.length <= FUTURE_SEGWIT_MAX_SIZE + ) { + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return bscript.compile([ + decodeBech32.version + FUTURE_SEGWIT_VERSION_DIFF, + decodeBech32.data, + ]); + } + } + } + throw new Error(address + ' has no matching Script'); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bip66.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bip66.js new file mode 100644 index 0000000..1252a65 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bip66.js @@ -0,0 +1,110 @@ +// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki +// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] +// NOTE: SIGHASH byte ignored AND restricted, truncate before use +/** + * Checks if the given buffer is a valid BIP66-encoded signature. + * + * @param buffer - The buffer to check. + * @returns A boolean indicating whether the buffer is a valid BIP66-encoded signature. + */ +export function check(buffer) { + if (buffer.length < 8) return false; + if (buffer.length > 72) return false; + if (buffer[0] !== 0x30) return false; + if (buffer[1] !== buffer.length - 2) return false; + if (buffer[2] !== 0x02) return false; + const lenR = buffer[3]; + if (lenR === 0) return false; + if (5 + lenR >= buffer.length) return false; + if (buffer[4 + lenR] !== 0x02) return false; + const lenS = buffer[5 + lenR]; + if (lenS === 0) return false; + if (6 + lenR + lenS !== buffer.length) return false; + if (buffer[4] & 0x80) return false; + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) return false; + if (buffer[lenR + 6] & 0x80) return false; + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + return false; + return true; +} +/** + * Decodes a DER-encoded signature buffer and returns the R and S values. + * @param buffer - The DER-encoded signature buffer. + * @returns An object containing the R and S values. + * @throws {Error} If the DER sequence length is too short, too long, or invalid. + * @throws {Error} If the R or S length is zero or invalid. + * @throws {Error} If the R or S value is negative or excessively padded. + */ +export function decode(buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short'); + if (buffer.length > 72) throw new Error('DER sequence length is too long'); + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence'); + if (buffer[1] !== buffer.length - 2) + throw new Error('DER sequence length is invalid'); + if (buffer[2] !== 0x02) throw new Error('Expected DER integer'); + const lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero'); + if (5 + lenR >= buffer.length) throw new Error('R length is too long'); + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)'); + const lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero'); + if (6 + lenR + lenS !== buffer.length) throw new Error('S length is invalid'); + if (buffer[4] & 0x80) throw new Error('R value is negative'); + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) + throw new Error('R value excessively padded'); + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative'); + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + throw new Error('S value excessively padded'); + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR), + }; +} +/* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ +export function encode(r, s) { + const lenR = r.length; + const lenS = s.length; + if (lenR === 0) throw new Error('R length is zero'); + if (lenS === 0) throw new Error('S length is zero'); + if (lenR > 33) throw new Error('R length is too long'); + if (lenS > 33) throw new Error('S length is too long'); + if (r[0] & 0x80) throw new Error('R value is negative'); + if (s[0] & 0x80) throw new Error('S value is negative'); + if (lenR > 1 && r[0] === 0x00 && !(r[1] & 0x80)) + throw new Error('R value excessively padded'); + if (lenS > 1 && s[0] === 0x00 && !(s[1] & 0x80)) + throw new Error('S value excessively padded'); + const signature = new Uint8Array(6 + lenR + lenS); + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + signature.set(r, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + signature.set(s, 6 + lenR); + return signature; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/block.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/block.js new file mode 100644 index 0000000..c717d3d --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/block.js @@ -0,0 +1,225 @@ +import { + BufferReader, + BufferWriter, + reverseBuffer, + varuint, +} from './bufferutils.js'; +import * as bcrypto from './crypto.js'; +import { fastMerkleRoot } from './merkle.js'; +import { Transaction } from './transaction.js'; +import * as v from 'valibot'; +import * as tools from 'uint8array-tools'; +const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', +); +const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', +); +export class Block { + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(tools.fromHex(hex)); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = new Uint8Array(32); + target[29 - exponent] = (mantissa >> 16) & 0xff; + target[30 - exponent] = (mantissa >> 8) & 0xff; + target[31 - exponent] = mantissa & 0xff; + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + v.parse(v.array(v.object({ getHash: v.function() })), transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto.hash256); + return forWitness + ? bcrypto.hash256( + tools.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + version = 1; + prevHash = undefined; + merkleRoot = undefined; + timestamp = 0; + witnessCommit = undefined; + bits = 0; + nonce = 0; + transactions = undefined; + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter( + out => + tools.compare( + out.script.slice(0, 6), + Uint8Array.from([0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed]), + ) === 0, + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Uint8Array && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Uint8Array && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto.hash256(this.toBuffer(true)); + } + getId() { + return tools.toHex(reverseBuffer(this.getHash())); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = new Uint8Array(this.byteLength(headersOnly)); + const bufferWriter = new BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + const { bytes } = varuint.encode( + this.transactions.length, + buffer, + bufferWriter.offset, + ); + bufferWriter.offset += bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return tools.toHex(this.toBuffer(headersOnly)); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return tools.compare(hash, target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return tools.compare(this.merkleRoot, actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return tools.compare(this.witnessCommit, actualWitnessCommit) === 0; + } +} +function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); +} +function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bufferutils.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bufferutils.js new file mode 100644 index 0000000..fb819fb --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/bufferutils.js @@ -0,0 +1,156 @@ +import * as types from './types.js'; +import * as varuint from 'varuint-bitcoin'; +import * as v from 'valibot'; +export { varuint }; +import * as tools from 'uint8array-tools'; +const MAX_JS_NUMBER = 0x001fffffffffffff; +// https://github.com/feross/buffer/blob/master/index.js#L1127 +function verifuint(value, max) { + if (typeof value !== 'number' && typeof value !== 'bigint') + throw new Error('cannot write a non-number as a number'); + if (value < 0 && value < BigInt(0)) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max && value > BigInt(max)) + throw new Error('RangeError: value out of range'); + if (Math.floor(Number(value)) !== Number(value)) + throw new Error('value has a fractional component'); +} +/** + * Reverses the order of bytes in a buffer. + * @param buffer - The buffer to reverse. + * @returns A new buffer with the bytes reversed. + */ +export function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +export function cloneBuffer(buffer) { + const clone = new Uint8Array(buffer.length); + clone.set(buffer); + return clone; +} +/** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ +export class BufferWriter { + buffer; + offset; + static withCapacity(size) { + return new BufferWriter(new Uint8Array(size)); + } + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + v.parse(v.tuple([types.BufferSchema, types.UInt32Schema]), [ + buffer, + offset, + ]); + } + writeUInt8(i) { + this.offset = tools.writeUInt8(this.buffer, this.offset, i); + } + writeInt32(i) { + this.offset = tools.writeInt32(this.buffer, this.offset, i, 'LE'); + } + writeInt64(i) { + this.offset = tools.writeInt64(this.buffer, this.offset, BigInt(i), 'LE'); + } + writeUInt32(i) { + this.offset = tools.writeUInt32(this.buffer, this.offset, i, 'LE'); + } + writeUInt64(i) { + this.offset = tools.writeUInt64(this.buffer, this.offset, BigInt(i), 'LE'); + } + writeVarInt(i) { + const { bytes } = varuint.encode(i, this.buffer, this.offset); + this.offset += bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.buffer.set(slice, this.offset); + this.offset += slice.length; + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + end() { + if (this.buffer.length === this.offset) { + return this.buffer; + } + throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`); + } +} +/** + * Helper class for reading of bitcoin data types from a buffer. + */ +export class BufferReader { + buffer; + offset; + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + v.parse(v.tuple([types.BufferSchema, types.UInt32Schema]), [ + buffer, + offset, + ]); + } + readUInt8() { + const result = tools.readUInt8(this.buffer, this.offset); + this.offset++; + return result; + } + readInt32() { + const result = tools.readInt32(this.buffer, this.offset, 'LE'); + this.offset += 4; + return result; + } + readUInt32() { + const result = tools.readUInt32(this.buffer, this.offset, 'LE'); + this.offset += 4; + return result; + } + readInt64() { + const result = tools.readInt64(this.buffer, this.offset, 'LE'); + this.offset += 8; + return result; + } + readVarInt() { + const { bigintValue, bytes } = varuint.decode(this.buffer, this.offset); + this.offset += bytes; + return bigintValue; + } + readSlice(n) { + verifuint(n, MAX_JS_NUMBER); + const num = Number(n); + if (this.buffer.length < this.offset + num) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + num); + this.offset += num; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/crypto.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/crypto.js new file mode 100644 index 0000000..88705eb --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/crypto.js @@ -0,0 +1,89 @@ +/** + * A module for hashing functions. + * include ripemd160、sha1、sha256、hash160、hash256、taggedHash + * + * @packageDocumentation + */ +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import * as tools from 'uint8array-tools'; +export function hash160(buffer) { + return ripemd160(sha256(buffer)); +} +export function hash256(buffer) { + return sha256(sha256(buffer)); +} +export const TAGS = [ + 'BIP0340/challenge', + 'BIP0340/aux', + 'BIP0340/nonce', + 'TapLeaf', + 'TapBranch', + 'TapSighash', + 'TapTweak', + 'KeyAgg list', + 'KeyAgg coefficient', +]; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +/** + * Defines the tagged hash prefixes used in the crypto module. + */ +export const TAGGED_HASH_PREFIXES = { + 'BIP0340/challenge': Uint8Array.from([ + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + ]), + 'BIP0340/aux': Uint8Array.from([ + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + ]), + 'BIP0340/nonce': Uint8Array.from([ + 7, 73, 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, + 52, 215, 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, 7, 73, + 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, 52, 215, + 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, + ]), + TapLeaf: Uint8Array.from([ + 174, 234, 143, 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, + 95, 28, 181, 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, 174, 234, 143, + 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, 95, 28, 181, + 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, + ]), + TapBranch: Uint8Array.from([ + 25, 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, + 33, 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, 25, + 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, 33, + 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, + ]), + TapSighash: Uint8Array.from([ + 244, 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, + 149, 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, 244, + 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, 149, + 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, + ]), + TapTweak: Uint8Array.from([ + 232, 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, + 156, 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, 232, + 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, 156, + 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, + ]), + 'KeyAgg list': Uint8Array.from([ + 72, 28, 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, + 215, 49, 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, 72, 28, + 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, 215, 49, + 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, + ]), + 'KeyAgg coefficient': Uint8Array.from([ + 191, 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, + 130, 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, 191, + 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, 130, + 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, + ]), +}; +export function taggedHash(prefix, data) { + return sha256(tools.concat([TAGGED_HASH_PREFIXES[prefix], data])); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ecc_lib.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ecc_lib.js new file mode 100644 index 0000000..0f96560 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ecc_lib.js @@ -0,0 +1,106 @@ +import * as tools from 'uint8array-tools'; +const _ECCLIB_CACHE = {}; +/** + * Initializes the ECC library with the provided instance. + * If `eccLib` is `undefined`, the library will be cleared. + * If `eccLib` is a new instance, it will be verified before setting it as the active library. + * + * @param eccLib The instance of the ECC library to initialize. + */ +export function initEccLib(eccLib) { + if (!eccLib) { + // allow clearing the library + _ECCLIB_CACHE.eccLib = eccLib; + } else if (eccLib !== _ECCLIB_CACHE.eccLib) { + // new instance, verify it + verifyEcc(eccLib); + _ECCLIB_CACHE.eccLib = eccLib; + } +} +/** + * Retrieves the ECC Library instance. + * Throws an error if the ECC Library is not provided. + * You must call initEccLib() with a valid TinySecp256k1Interface instance before calling this function. + * @returns The ECC Library instance. + * @throws Error if the ECC Library is not provided. + */ +export function getEccLib() { + if (!_ECCLIB_CACHE.eccLib) + throw new Error( + 'No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance', + ); + return _ECCLIB_CACHE.eccLib; +} +const h = hex => tools.fromHex(hex); +/** + * Verifies the ECC functionality. + * + * @param ecc - The TinySecp256k1Interface object. + */ +function verifyEcc(ecc) { + assert(typeof ecc.isXOnlyPoint === 'function'); + assert( + ecc.isXOnlyPoint( + h('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000001'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000000'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + ), + ); + assert(typeof ecc.xOnlyPointAddTweak === 'function'); + tweakAddVectors.forEach(t => { + const r = ecc.xOnlyPointAddTweak(h(t.pubkey), h(t.tweak)); + if (t.result === null) { + assert(r === null); + } else { + assert(r !== null); + assert(r.parity === t.parity); + assert(tools.compare(r.xOnlyPubkey, h(t.result)) === 0); + } + }); +} +function assert(bool) { + if (!bool) throw new Error('ecc library invalid'); +} +const tweakAddVectors = [ + { + pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + tweak: 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + parity: -1, + result: null, + }, + { + pubkey: '1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b', + tweak: 'a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac', + parity: 1, + result: 'e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf', + }, + { + pubkey: '2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991', + tweak: '823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47', + parity: 0, + result: '9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c', + }, +]; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/index.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/index.js new file mode 100644 index 0000000..fccfcb1 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/index.js @@ -0,0 +1,12 @@ +import * as address from './address.js'; +import * as crypto from './crypto.js'; +import * as networks from './networks.js'; +import * as payments from './payments/index.js'; +import * as script from './script.js'; +export { address, crypto, networks, payments, script }; +export { Block } from './block.js'; +export { Psbt } from './psbt.js'; +/** @hidden */ +export { OPS as opcodes } from './ops.js'; +export { Transaction } from './transaction.js'; +export { initEccLib } from './ecc_lib.js'; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/merkle.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/merkle.js new file mode 100644 index 0000000..0a67870 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/merkle.js @@ -0,0 +1,27 @@ +import * as tools from 'uint8array-tools'; +/** + * Calculates the Merkle root of an array of buffers using a specified digest function. + * + * @param values - The array of buffers. + * @param digestFn - The digest function used to calculate the hash of the concatenated buffers. + * @returns The Merkle root as a buffer. + * @throws {TypeError} If the values parameter is not an array or the digestFn parameter is not a function. + */ +export function fastMerkleRoot(values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array'); + if (typeof digestFn !== 'function') + throw TypeError('Expected digest Function'); + let length = values.length; + const results = values.concat(); + while (length > 1) { + let j = 0; + for (let i = 0; i < length; i += 2, ++j) { + const left = results[i]; + const right = i + 1 === length ? left : results[i + 1]; + const data = tools.concat([left, right]); + results[j] = digestFn(data); + } + length = j; + } + return results[0]; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/networks.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/networks.js new file mode 100644 index 0000000..c415efd --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/networks.js @@ -0,0 +1,68 @@ +// https://en.bitcoin.it/wiki/List_of_address_prefixes +// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 +/** + * Represents the Bitcoin network configuration. + */ +export const bitcoin = { + /** + * The message prefix used for signing Bitcoin messages. + */ + messagePrefix: '\x18Bitcoin Signed Message:\n', + /** + * The Bech32 prefix used for Bitcoin addresses. + */ + bech32: 'bc', + /** + * The BIP32 key prefixes for Bitcoin. + */ + bip32: { + /** + * The public key prefix for BIP32 extended public keys. + */ + public: 0x0488b21e, + /** + * The private key prefix for BIP32 extended private keys. + */ + private: 0x0488ade4, + }, + /** + * The prefix for Bitcoin public key hashes. + */ + pubKeyHash: 0x00, + /** + * The prefix for Bitcoin script hashes. + */ + scriptHash: 0x05, + /** + * The prefix for Bitcoin Wallet Import Format (WIF) private keys. + */ + wif: 0x80, +}; +/** + * Represents the regtest network configuration. + */ +export const regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; +/** + * Represents the testnet network configuration. + */ +export const testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ops.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ops.js new file mode 100644 index 0000000..9e24a7c --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/ops.js @@ -0,0 +1,127 @@ +const OPS = { + OP_FALSE: 0, + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_RESERVED: 80, + OP_TRUE: 81, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + OP_NOP: 97, + OP_VER: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_VERIF: 101, + OP_VERNOTIF: 102, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + OP_CAT: 126, + OP_SUBSTR: 127, + OP_LEFT: 128, + OP_RIGHT: 129, + OP_SIZE: 130, + OP_INVERT: 131, + OP_AND: 132, + OP_OR: 133, + OP_XOR: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_RESERVED1: 137, + OP_RESERVED2: 138, + OP_1ADD: 139, + OP_1SUB: 140, + OP_2MUL: 141, + OP_2DIV: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + OP_ADD: 147, + OP_SUB: 148, + OP_MUL: 149, + OP_DIV: 150, + OP_MOD: 151, + OP_LSHIFT: 152, + OP_RSHIFT: 153, + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + OP_WITHIN: 165, + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + OP_NOP1: 176, + OP_NOP2: 177, + OP_CHECKLOCKTIMEVERIFY: 177, + OP_NOP3: 178, + OP_CHECKSEQUENCEVERIFY: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + OP_CHECKSIGADD: 186, + OP_PUBKEYHASH: 253, + OP_PUBKEY: 254, + OP_INVALIDOPCODE: 255, +}; +const REVERSE_OPS = {}; +for (const op of Object.keys(OPS)) { + const code = OPS[op]; + REVERSE_OPS[code] = op; +} +export { OPS, REVERSE_OPS }; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/bip341.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/bip341.js new file mode 100644 index 0000000..2317358 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/bip341.js @@ -0,0 +1,135 @@ +import { getEccLib } from '../ecc_lib.js'; +import * as bcrypto from '../crypto.js'; +import { varuint } from '../bufferutils.js'; +import { isTapleaf } from '../types.js'; +import * as tools from 'uint8array-tools'; +export const LEAF_VERSION_TAPSCRIPT = 0xc0; +export const MAX_TAPTREE_DEPTH = 128; +const isHashBranch = ht => 'left' in ht && 'right' in ht; +/** + * Calculates the root hash from a given control block and leaf hash. + * @param controlBlock - The control block buffer. + * @param leafHash - The leaf hash buffer. + * @returns The root hash buffer. + * @throws {TypeError} If the control block length is less than 33. + */ +export function rootHashFromPath(controlBlock, leafHash) { + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + const m = (controlBlock.length - 33) / 32; + let kj = leafHash; + for (let j = 0; j < m; j++) { + const ej = controlBlock.slice(33 + 32 * j, 65 + 32 * j); + if (tools.compare(kj, ej) < 0) { + kj = tapBranchHash(kj, ej); + } else { + kj = tapBranchHash(ej, kj); + } + } + return kj; +} +/** + * Build a hash tree of merkle nodes from the scripts binary tree. + * @param scriptTree - the tree of scripts to pairwise hash. + */ +export function toHashTree(scriptTree) { + if (isTapleaf(scriptTree)) return { hash: tapleafHash(scriptTree) }; + const hashes = [toHashTree(scriptTree[0]), toHashTree(scriptTree[1])]; + // hashes.sort((a, b) => a.hash.compare(b.hash)); + hashes.sort((a, b) => tools.compare(a.hash, b.hash)); + const [left, right] = hashes; + return { + hash: tapBranchHash(left.hash, right.hash), + left, + right, + }; +} +/** + * Given a HashTree, finds the path from a particular hash to the root. + * @param node - the root of the tree + * @param hash - the hash to search for + * @returns - array of sibling hashes, from leaf (inclusive) to root + * (exclusive) needed to prove inclusion of the specified hash. undefined if no + * path is found + */ +export function findScriptPath(node, hash) { + if (isHashBranch(node)) { + const leftPath = findScriptPath(node.left, hash); + if (leftPath !== undefined) return [...leftPath, node.right.hash]; + const rightPath = findScriptPath(node.right, hash); + if (rightPath !== undefined) return [...rightPath, node.left.hash]; + } else if (tools.compare(node.hash, hash) === 0) { + return []; + } + return undefined; +} +/** + * Calculates the tapleaf hash for a given Tapleaf object. + * @param leaf - The Tapleaf object to calculate the hash for. + * @returns The tapleaf hash as a Buffer. + */ +export function tapleafHash(leaf) { + const version = leaf.version || LEAF_VERSION_TAPSCRIPT; + return bcrypto.taggedHash( + 'TapLeaf', + tools.concat([Uint8Array.from([version]), serializeScript(leaf.output)]), + ); +} +/** + * Computes the taproot tweak hash for a given public key and optional hash. + * If a hash is provided, the public key and hash are concatenated before computing the hash. + * If no hash is provided, only the public key is used to compute the hash. + * + * @param pubKey - The public key buffer. + * @param h - The optional hash buffer. + * @returns The taproot tweak hash. + */ +export function tapTweakHash(pubKey, h) { + return bcrypto.taggedHash( + 'TapTweak', + tools.concat(h ? [pubKey, h] : [pubKey]), + ); +} +/** + * Tweak a public key with a given tweak hash. + * @param pubKey - The public key to be tweaked. + * @param h - The tweak hash. + * @returns The tweaked public key or null if the input is invalid. + */ +export function tweakKey(pubKey, h) { + if (!(pubKey instanceof Uint8Array)) return null; + if (pubKey.length !== 32) return null; + if (h && h.length !== 32) return null; + const tweakHash = tapTweakHash(pubKey, h); + const res = getEccLib().xOnlyPointAddTweak(pubKey, tweakHash); + if (!res || res.xOnlyPubkey === null) return null; + return { + parity: res.parity, + x: Uint8Array.from(res.xOnlyPubkey), + }; +} +/** + * Computes the TapBranch hash by concatenating two buffers and applying the 'TapBranch' tagged hash algorithm. + * + * @param a - The first buffer. + * @param b - The second buffer. + * @returns The TapBranch hash of the concatenated buffers. + */ +function tapBranchHash(a, b) { + return bcrypto.taggedHash('TapBranch', tools.concat([a, b])); +} +/** + * Serializes a script by encoding its length as a varint and concatenating it with the script. + * + * @param s - The script to be serialized. + * @returns The serialized script as a Buffer. + */ +function serializeScript(s) { + /* global BigInt */ + const varintLen = varuint.encodingLength(s.length); + const buffer = new Uint8Array(varintLen); + varuint.encode(s.length, buffer); + return tools.concat([buffer, s]); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/embed.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/embed.js new file mode 100644 index 0000000..d16db9c --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/embed.js @@ -0,0 +1,50 @@ +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { stacksEqual, BufferSchema } from '../types.js'; +import * as lazy from './lazy.js'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +// output: OP_RETURN ... +/** + * Embeds data in a Bitcoin payment. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The modified payment object. + * @throws {TypeError} If there is not enough data or if the output is invalid. + */ +export function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + output: BufferSchema, + data: v.array(BufferSchema), + }), + ), + a, + ); + const network = a.network || BITCOIN_NETWORK; + const o = { name: 'embed', network }; + lazy.prop(o, 'output', () => { + if (!a.data) return; + return bscript.compile([OPS.OP_RETURN].concat(a.data)); + }); + lazy.prop(o, 'data', () => { + if (!a.output) return; + return bscript.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript.decompile(a.output); + if (chunks[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(chunk => v.is(BufferSchema, chunk))) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/index.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/index.js new file mode 100644 index 0000000..3c2fd1e --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/index.js @@ -0,0 +1,11 @@ +import { p2data as embed } from './embed.js'; +import { p2ms } from './p2ms.js'; +import { p2pk } from './p2pk.js'; +import { p2pkh } from './p2pkh.js'; +import { p2sh } from './p2sh.js'; +import { p2wpkh } from './p2wpkh.js'; +import { p2wsh } from './p2wsh.js'; +import { p2tr } from './p2tr.js'; +export { embed, p2ms, p2pk, p2pkh, p2sh, p2wpkh, p2wsh, p2tr }; +// TODO +// witness commitment diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/lazy.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/lazy.js new file mode 100644 index 0000000..cc66c91 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/lazy.js @@ -0,0 +1,27 @@ +export function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); +} +export function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2ms.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2ms.js new file mode 100644 index 0000000..200ee1b --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2ms.js @@ -0,0 +1,149 @@ +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { BufferSchema, isPoint, stacksEqual } from '../types.js'; +import * as lazy from './lazy.js'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +const OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1 +// input: OP_0 [signatures ...] +// output: m [pubKeys ...] n OP_CHECKMULTISIG +/** + * Represents a function that creates a Pay-to-Multisig (P2MS) payment object. + * @param a - The payment object. + * @param opts - Optional payment options. + * @returns The created payment object. + * @throws {TypeError} If the provided data is not valid. + */ +export function p2ms(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS.OP_0) !== undefined + ); + } + v.parse( + v.partial( + v.object({ + network: v.object({}), + m: v.number(), + n: v.number(), + output: BufferSchema, + pubkeys: v.array(v.custom(isPoint), 'Received invalid pubkey'), + signatures: v.array( + v.custom(isAcceptableSignature), + 'Expected signature to be of type isAcceptableSignature', + ), + input: BufferSchema, + }), + ), + a, + ); + const network = a.network || BITCOIN_NETWORK; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript.decompile(output); + o.m = chunks[0] - OP_INT_BASE; + o.n = chunks[chunks.length - 2] - OP_INT_BASE; + o.pubkeys = chunks.slice(1, -2); + } + lazy.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript.compile( + [].concat( + OP_INT_BASE + a.m, + a.pubkeys, + OP_INT_BASE + o.n, + OPS.OP_CHECKMULTISIG, + ), + ); + }); + lazy.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript.decompile(a.input).slice(1); + }); + lazy.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript.compile([OPS.OP_0].concat(a.signatures)); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + v.parse(v.number(), chunks[0], { message: 'Output is invalid' }); + v.parse(v.number(), chunks[chunks.length - 2], { + message: 'Output is invalid', + }); + if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pk.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pk.js new file mode 100644 index 0000000..8dba5e1 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pk.js @@ -0,0 +1,82 @@ +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { BufferSchema, isPoint } from '../types.js'; +import * as lazy from './lazy.js'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +// input: {signature} +// output: {pubKey} OP_CHECKSIG +/** + * Creates a pay-to-public-key (P2PK) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PK payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export function p2pk(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + output: BufferSchema, + pubkey: v.custom(isPoint, 'invalid pubkey'), + signature: v.custom( + bscript.isCanonicalScriptSignature, + 'Expected signature to be of type isCanonicalScriptSignature', + ), + input: BufferSchema, + }), + ), + a, + ); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || BITCOIN_NETWORK; + const o = { name: 'p2pk', network }; + lazy.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript.compile([a.pubkey, OPS.OP_CHECKSIG]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.signature) return; + return bscript.compile([a.signature]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!isPoint(o.pubkey)) throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && tools.compare(a.pubkey, o.pubkey) !== 0) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && tools.compare(a.input, o.input) !== 0) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pkh.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pkh.js new file mode 100644 index 0000000..41101eb --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2pkh.js @@ -0,0 +1,144 @@ +import * as bcrypto from '../crypto.js'; +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { + isPoint, + Hash160bitSchema, + NBufferSchemaFactory, + BufferSchema, +} from '../types.js'; +import * as lazy from './lazy.js'; +import bs58check from 'bs58check'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +// input: {signature} {pubkey} +// output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG +/** + * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2PKH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export function p2pkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + address: v.string(), + hash: Hash160bitSchema, + output: NBufferSchemaFactory(25), + pubkey: v.custom(isPoint), + signature: v.custom(bscript.isCanonicalScriptSignature), + input: BufferSchema, + }), + ), + a, + ); + const _address = lazy.value(() => { + const payload = bs58check.decode(a.address); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || BITCOIN_NETWORK; + const o = { name: 'p2pkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, network.pubKeyHash); + payload.set(o.hash, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([ + OPS.OP_DUP, + OPS.OP_HASH160, + o.hash, + OPS.OP_EQUALVERIFY, + OPS.OP_CHECKSIG, + ]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript.compile([a.signature, a.pubkey]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS.OP_DUP || + a.output[1] !== OPS.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS.OP_EQUALVERIFY || + a.output[24] !== OPS.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey'); + if (a.signature && tools.compare(a.signature, chunks[0]) !== 0) + throw new TypeError('Signature mismatch'); + if (a.pubkey && tools.compare(a.pubkey, chunks[1]) !== 0) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(chunks[1]); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2sh.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2sh.js new file mode 100644 index 0000000..ed2d28c --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2sh.js @@ -0,0 +1,201 @@ +import * as bcrypto from '../crypto.js'; +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { BufferSchema, NBufferSchemaFactory, stacksEqual } from '../types.js'; +import * as lazy from './lazy.js'; +import bs58check from 'bs58check'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +// input: [redeemScriptSig ...] {redeemScript} +// witness: +// output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL +/** + * Creates a Pay-to-Script-Hash (P2SH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2SH payment object. + * @throws {TypeError} If the required data is not provided or if the data is invalid. + */ +export function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + network: v.object({}), + address: v.string(), + hash: NBufferSchemaFactory(20), + output: NBufferSchemaFactory(23), + redeem: v.partial( + v.object({ + network: v.object({}), + output: BufferSchema, + input: BufferSchema, + witness: v.array(BufferSchema), + }), + ), + input: BufferSchema, + witness: v.array(BufferSchema), + }), + ), + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || BITCOIN_NETWORK; + } + const o = { network }; + const _address = lazy.value(() => { + const payload = bs58check.decode(a.address); + const version = tools.readUInt8(payload, 0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const _redeem = lazy.value(() => { + const chunks = _chunks(); + const lastChunk = chunks[chunks.length - 1]; + return { + network, + output: lastChunk === OPS.OP_FALSE ? Uint8Array.from([]) : lastChunk, + input: bscript.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = new Uint8Array(21); + tools.writeUInt8(payload, 0, o.network.scriptHash); + payload.set(o.hash, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_HASH160, o.hash, OPS.OP_EQUAL]); + }); + // input dependents + lazy.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript.compile( + [].concat(bscript.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + if (redeem.output.byteLength > 520) + throw new TypeError( + 'Redeem.output unspendable if larger than 520 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = bcrypto.hash160(redeem.output); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript.decompile(redeem.input); + if (!bscript.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!(_redeem().output instanceof Uint8Array)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if ( + a.redeem.output && + tools.compare(a.redeem.output, redeem.output) !== 0 + ) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && tools.compare(a.redeem.input, redeem.input) !== 0) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2tr.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2tr.js new file mode 100644 index 0000000..d12fabd --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2tr.js @@ -0,0 +1,301 @@ +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { + isTaptree, + TAPLEAF_VERSION_MASK, + stacksEqual, + NBufferSchemaFactory, + BufferSchema, +} from '../types.js'; +import { getEccLib } from '../ecc_lib.js'; +import { + toHashTree, + rootHashFromPath, + findScriptPath, + tapleafHash, + tweakKey, + LEAF_VERSION_TAPSCRIPT, +} from './bip341.js'; +import * as lazy from './lazy.js'; +import { bech32m } from 'bech32'; +import { fromBech32 } from '../address.js'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +const TAPROOT_WITNESS_VERSION = 0x01; +const ANNEX_PREFIX = 0x50; +/** + * Creates a Pay-to-Taproot (P2TR) payment object. + * + * @param a - The payment object containing the necessary data for P2TR. + * @param opts - Optional payment options. + * @returns The P2TR payment object. + * @throws {TypeError} If the provided data is invalid or insufficient. + */ +export function p2tr(a, opts) { + if ( + !a.address && + !a.output && + !a.pubkey && + !a.internalPubkey && + !(a.witness && a.witness.length > 1) + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + address: v.string(), + input: NBufferSchemaFactory(0), + network: v.object({}), + output: NBufferSchemaFactory(34), + internalPubkey: NBufferSchemaFactory(32), + hash: NBufferSchemaFactory(32), // merkle root hash, the tweak + pubkey: NBufferSchemaFactory(32), // tweaked with `hash` from `internalPubkey` + signature: v.union([ + NBufferSchemaFactory(64), + NBufferSchemaFactory(65), + ]), + witness: v.array(BufferSchema), + scriptTree: v.custom(isTaptree, 'Taptree is not of type isTaptree'), + redeem: v.partial( + v.object({ + output: BufferSchema, // tapleaf script + redeemVersion: v.number(), // tapleaf version + witness: v.array(BufferSchema), + }), + ), + redeemVersion: v.number(), + }), + ), + a, + ); + const _address = lazy.value(() => { + return fromBech32(a.address); + }); + // remove annex if present, ignored by taproot + const _witness = lazy.value(() => { + if (!a.witness || !a.witness.length) return; + if ( + a.witness.length >= 2 && + a.witness[a.witness.length - 1][0] === ANNEX_PREFIX + ) { + return a.witness.slice(0, -1); + } + return a.witness.slice(); + }); + const _hashTree = lazy.value(() => { + if (a.scriptTree) return toHashTree(a.scriptTree); + if (a.hash) return { hash: a.hash }; + return; + }); + const network = a.network || BITCOIN_NETWORK; + const o = { name: 'p2tr', network }; + lazy.prop(o, 'address', () => { + if (!o.pubkey) return; + const words = bech32m.toWords(o.pubkey); + words.unshift(TAPROOT_WITNESS_VERSION); + return bech32m.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + const hashTree = _hashTree(); + if (hashTree) return hashTree.hash; + const w = _witness(); + if (w && w.length > 1) { + const controlBlock = w[w.length - 1]; + const leafVersion = controlBlock[0] & TAPLEAF_VERSION_MASK; + const script = w[w.length - 2]; + const leafHash = tapleafHash({ output: script, version: leafVersion }); + return rootHashFromPath(controlBlock, leafHash); + } + return null; + }); + lazy.prop(o, 'output', () => { + if (!o.pubkey) return; + return bscript.compile([OPS.OP_1, o.pubkey]); + }); + lazy.prop(o, 'redeemVersion', () => { + if (a.redeemVersion) return a.redeemVersion; + if ( + a.redeem && + a.redeem.redeemVersion !== undefined && + a.redeem.redeemVersion !== null + ) { + return a.redeem.redeemVersion; + } + return LEAF_VERSION_TAPSCRIPT; + }); + lazy.prop(o, 'redeem', () => { + const witness = _witness(); // witness without annex + if (!witness || witness.length < 2) return; + return { + output: witness[witness.length - 2], + witness: witness.slice(0, -2), + redeemVersion: witness[witness.length - 1][0] & TAPLEAF_VERSION_MASK, + }; + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.internalPubkey) { + const tweakedKey = tweakKey(o.internalPubkey, o.hash); + if (tweakedKey) return tweakedKey.x; + } + }); + lazy.prop(o, 'internalPubkey', () => { + if (a.internalPubkey) return a.internalPubkey; + const witness = _witness(); + if (witness && witness.length > 1) + return witness[witness.length - 1].slice(1, 33); + }); + lazy.prop(o, 'signature', () => { + if (a.signature) return a.signature; + const witness = _witness(); // witness without annex + if (!witness || witness.length !== 1) return; + return witness[0]; + }); + lazy.prop(o, 'witness', () => { + if (a.witness) return a.witness; + const hashTree = _hashTree(); + if (hashTree && a.redeem && a.redeem.output && a.internalPubkey) { + const leafHash = tapleafHash({ + output: a.redeem.output, + version: o.redeemVersion, + }); + const path = findScriptPath(hashTree, leafHash); + if (!path) return; + const outputKey = tweakKey(a.internalPubkey, hashTree.hash); + if (!outputKey) return; + const controlBock = tools.concat( + [ + Uint8Array.from([o.redeemVersion | outputKey.parity]), + a.internalPubkey, + ].concat(path), + ); + return [a.redeem.output, controlBock]; + } + if (a.signature) return [a.signature]; + }); + // extended validation + if (opts.validate) { + let pubkey = Uint8Array.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== TAPROOT_WITNESS_VERSION) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + pubkey = _address().data; + } + if (a.pubkey) { + if (pubkey.length > 0 && tools.compare(pubkey, a.pubkey) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.pubkey; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_1 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + if (pubkey.length > 0 && tools.compare(pubkey, a.output.slice(2)) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.output.slice(2); + } + if (a.internalPubkey) { + const tweakedKey = tweakKey(a.internalPubkey, o.hash); + if (pubkey.length > 0 && tools.compare(pubkey, tweakedKey.x) !== 0) + throw new TypeError('Pubkey mismatch'); + else pubkey = tweakedKey.x; + } + if (pubkey && pubkey.length) { + if (!getEccLib().isXOnlyPoint(pubkey)) + throw new TypeError('Invalid pubkey for p2tr'); + } + const hashTree = _hashTree(); + if (a.hash && hashTree) { + if (tools.compare(a.hash, hashTree.hash) !== 0) + throw new TypeError('Hash mismatch'); + } + if (a.redeem && a.redeem.output && hashTree) { + const leafHash = tapleafHash({ + output: a.redeem.output, + version: o.redeemVersion, + }); + if (!findScriptPath(hashTree, leafHash)) + throw new TypeError('Redeem script not in tree'); + } + const witness = _witness(); + // compare the provided redeem data with the one computed from witness + if (a.redeem && o.redeem) { + if (a.redeem.redeemVersion) { + if (a.redeem.redeemVersion !== o.redeem.redeemVersion) + throw new TypeError('Redeem.redeemVersion and witness mismatch'); + } + if (a.redeem.output) { + if (bscript.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // output redeem is constructed from the witness + if ( + o.redeem.output && + tools.compare(a.redeem.output, o.redeem.output) !== 0 + ) + throw new TypeError('Redeem.output and witness mismatch'); + } + if (a.redeem.witness) { + if ( + o.redeem.witness && + !stacksEqual(a.redeem.witness, o.redeem.witness) + ) + throw new TypeError('Redeem.witness and witness mismatch'); + } + } + if (witness && witness.length) { + if (witness.length === 1) { + // key spending + if (a.signature && tools.compare(a.signature, witness[0]) !== 0) + throw new TypeError('Signature mismatch'); + } else { + // script path spending + const controlBlock = witness[witness.length - 1]; + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + if ((controlBlock.length - 33) % 32 !== 0) + throw new TypeError( + `The control-block length of ${controlBlock.length} is incorrect!`, + ); + const m = (controlBlock.length - 33) / 32; + if (m > 128) + throw new TypeError( + `The script path is too long. Got ${m}, expected max 128.`, + ); + const internalPubkey = controlBlock.slice(1, 33); + if ( + a.internalPubkey && + tools.compare(a.internalPubkey, internalPubkey) !== 0 + ) + throw new TypeError('Internal pubkey mismatch'); + if (!getEccLib().isXOnlyPoint(internalPubkey)) + throw new TypeError('Invalid internalPubkey for p2tr witness'); + const leafVersion = controlBlock[0] & TAPLEAF_VERSION_MASK; + const script = witness[witness.length - 2]; + const leafHash = tapleafHash({ output: script, version: leafVersion }); + const hash = rootHashFromPath(controlBlock, leafHash); + const outputKey = tweakKey(internalPubkey, hash); + if (!outputKey) + // todo: needs test data + throw new TypeError('Invalid outputKey for p2tr witness'); + if (pubkey.length && tools.compare(pubkey, outputKey.x) !== 0) + throw new TypeError('Pubkey mismatch for p2tr witness'); + if (outputKey.parity !== (controlBlock[0] & 1)) + throw new Error('Incorrect parity'); + } + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wpkh.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wpkh.js new file mode 100644 index 0000000..7b55073 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wpkh.js @@ -0,0 +1,139 @@ +import * as bcrypto from '../crypto.js'; +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { BufferSchema, isPoint, NBufferSchemaFactory } from '../types.js'; +import * as lazy from './lazy.js'; +import { bech32 } from 'bech32'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +const EMPTY_BUFFER = new Uint8Array(0); +// witness: {signature} {pubKey} +// input: <> +// output: OP_0 {pubKeyHash} +/** + * Creates a pay-to-witness-public-key-hash (p2wpkh) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The p2wpkh payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +export function p2wpkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + v.partial( + v.object({ + address: v.string(), + hash: NBufferSchemaFactory(20), + input: NBufferSchemaFactory(0), + network: v.object({}), + output: NBufferSchemaFactory(22), + pubkey: v.custom(isPoint, 'Not a valid pubkey'), + signature: v.custom(bscript.isCanonicalScriptSignature), + witness: v.array(BufferSchema), + }), + ), + a, + ); + const _address = lazy.value(() => { + const result = bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; + }); + const network = a.network || BITCOIN_NETWORK; + const o = { name: 'p2wpkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32.toWords(o.hash); + words.unshift(0x00); + return bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && tools.compare(hash, a.output.slice(2)) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && tools.compare(a.signature, a.witness[0]) !== 0) + throw new TypeError('Signature mismatch'); + // if (a.pubkey && !a.pubkey.equals(a.witness[1])) + if (a.pubkey && tools.compare(a.pubkey, a.witness[1]) !== 0) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(a.witness[1]); + if (hash.length > 0 && tools.compare(hash, pkh) !== 0) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wsh.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wsh.js new file mode 100644 index 0000000..0ca099b --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/payments/p2wsh.js @@ -0,0 +1,228 @@ +import { sha256 } from '@noble/hashes/sha256'; +import { bitcoin as BITCOIN_NETWORK } from '../networks.js'; +import * as bscript from '../script.js'; +import { + Buffer256bitSchema, + BufferSchema, + isPoint, + NBufferSchemaFactory, + stacksEqual, + NullablePartial, +} from '../types.js'; +import * as lazy from './lazy.js'; +import { bech32 } from 'bech32'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OPS = bscript.OPS; +const EMPTY_BUFFER = new Uint8Array(0); +function chunkHasUncompressedPubkey(chunk) { + if ( + chunk instanceof Uint8Array && + chunk.length === 65 && + chunk[0] === 0x04 && + isPoint(chunk) + ) { + return true; + } else { + return false; + } +} +// input: <> +// witness: [redeemScriptSig ...] {redeemScript} +// output: OP_0 {sha256(redeemScript)} +/** + * Creates a Pay-to-Witness-Script-Hash (P2WSH) payment object. + * + * @param a - The payment object containing the necessary data. + * @param opts - Optional payment options. + * @returns The P2WSH payment object. + * @throws {TypeError} If the required data is missing or invalid. + */ +export function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + v.parse( + NullablePartial({ + network: v.object({}), + address: v.string(), + hash: Buffer256bitSchema, + output: NBufferSchemaFactory(34), + redeem: NullablePartial({ + input: BufferSchema, + network: v.object({}), + output: BufferSchema, + witness: v.array(BufferSchema), + }), + input: NBufferSchemaFactory(0), + witness: v.array(BufferSchema), + }), + a, + ); + const _address = lazy.value(() => { + const result = bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Uint8Array.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || BITCOIN_NETWORK; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32.toWords(o.hash); + words.unshift(0x00); + return bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Uint8Array.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && tools.compare(hash, a.hash) !== 0) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty/valid? + if (a.redeem.output) { + const decompile = bscript.decompile(a.redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output is invalid'); + if (a.redeem.output.byteLength > 3600) + throw new TypeError( + 'Redeem.output unspendable if larger than 3600 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = sha256(a.redeem.output); + if (hash.length > 0 && tools.compare(hash, hash2) !== 0) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if ( + a.redeem && + a.redeem.output && + tools.compare(a.redeem.output, wScript) !== 0 + ) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt.js new file mode 100644 index 0000000..7af7cd7 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt.js @@ -0,0 +1,1721 @@ +import { Psbt as PsbtBase } from 'bip174'; +import * as varuint from 'varuint-bitcoin'; +import { checkForInput, checkForOutput } from 'bip174'; +import { fromOutputScript, toOutputScript } from './address.js'; +import { cloneBuffer, reverseBuffer } from './bufferutils.js'; +import { bitcoin as btcNetwork } from './networks.js'; +import * as payments from './payments/index.js'; +import { tapleafHash } from './payments/bip341.js'; +import * as bscript from './script.js'; +import { Transaction } from './transaction.js'; +import { + toXOnly, + tapScriptFinalizer, + serializeTaprootSignature, + isTaprootInput, + checkTaprootInputFields, + checkTaprootOutputFields, + checkTaprootInputForSigs, +} from './psbt/bip371.js'; +import { + witnessStackToScriptWitness, + checkInputForSig, + pubkeyInScript, + isP2MS, + isP2PK, + isP2PKH, + isP2WPKH, + isP2WSHScript, + isP2SHScript, + isP2TR, +} from './psbt/psbtutils.js'; +import * as tools from 'uint8array-tools'; +/** + * These are the default arguments for a Psbt instance. + */ +const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: btcNetwork, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, // satoshi per byte +}; +/** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ +export class Psbt { + data; + static fromBase64(data, opts = {}) { + const buffer = tools.fromBase64(data); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = tools.fromHex(data); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = PsbtBase.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + __CACHE; + opts; + constructor(opts = {}, data = new PsbtBase(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Psbt's predecessor (TransactionBuilder - now removed) behavior + // was to not confirm input values before signing. + // Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + checkTaprootInputFields(inputData, inputData, 'addInput'); + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = toOutputScript(address, network); + outputData = Object.assign({}, outputData, { script }); + } + checkTaprootOutputFields(outputData, outputData, 'addOutput'); + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + checkForInput(this.data.inputs, 0); // making sure we have at least one + range(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc) { + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + undefined, + finalScriptsFunc, + ); + return this._finalizeInput(inputIndex, input, finalScriptsFunc); + } + finalizeTaprootInput( + inputIndex, + tapLeafHashToFinalize, + finalScriptsFunc = tapScriptFinalizer, + ) { + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc, + ); + throw new Error(`Cannot finalize input #${inputIndex}. Not Taproot.`); + } + _finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts) { + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + _finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc = tapScriptFinalizer, + ) { + if (!input.witnessUtxo) + throw new Error( + `Cannot finalize input #${inputIndex}. Missing withness utxo.`, + ); + // Check key spend first. Increased privacy and reduced block space. + if (input.tapKeySig) { + const payment = payments.p2tr({ + output: input.witnessUtxo.script, + signature: input.tapKeySig, + }); + const finalScriptWitness = witnessStackToScriptWitness(payment.witness); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } else { + const { finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + tapLeafHashToFinalize, + ); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs(validator) { + checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx, validator), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + if (isTaprootInput(input)) + return this.validateSignaturesOfTaprootInput( + inputIndex, + validator, + pubkey, + ); + return this._validateSignaturesOfInput(inputIndex, validator, pubkey); + } + _validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + const mySigs = pubkey + ? partialSig.filter(sig => tools.compare(sig.pubkey, pubkey) === 0) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + results.push(validator(pSig.pubkey, hash, sig.signature)); + } + return results.every(res => res === true); + } + validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const tapKeySig = (input || {}).tapKeySig; + const tapScriptSig = (input || {}).tapScriptSig; + if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length)) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + pubkey = pubkey && toXOnly(pubkey); + const allHashses = pubkey + ? getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + pubkey, + this.__CACHE, + ) + : getAllTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + this.__CACHE, + ); + if (!allHashses.length) throw new Error('No signatures for this pubkey'); + const tapKeyHash = allHashses.find(h => !h.leafHash); + let validationResultCount = 0; + if (tapKeySig && tapKeyHash) { + const isValidTapkeySig = validator( + tapKeyHash.pubkey, + tapKeyHash.hash, + trimTaprootSig(tapKeySig), + ); + if (!isValidTapkeySig) return false; + validationResultCount++; + } + if (tapScriptSig) { + for (const tapSig of tapScriptSig) { + const tapSigHash = allHashses.find( + h => tools.compare(h.pubkey, tapSig.pubkey) === 0, + ); + if (tapSigHash) { + const isValidTapScriptSig = validator( + tapSig.pubkey, + tapSigHash.hash, + trimTaprootSig(tapSig.signature), + ); + if (!isValidTapScriptSig) return false; + validationResultCount++; + } + } + } + return validationResultCount > 0; + } + signAllInputsHD(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs(keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync(keyPair, sighashTypes) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput(inputIndex, keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) { + return this._signTaprootInput( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + } + return this._signInput(inputIndex, keyPair, sighashTypes); + } + signTaprootInput(inputIndex, keyPair, tapLeafHashToSign, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) + return this._signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + } + _signInput(inputIndex, keyPair, sighashTypes = [Transaction.SIGHASH_ALL]) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + _signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes = [Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ); + const tapKeySig = hashesForSig + .filter(h => !h.leafHash) + .map(h => + serializeTaprootSignature( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + )[0]; + const tapScriptSig = hashesForSig + .filter(h => !!h.leafHash) + .map(h => ({ + pubkey: toXOnly(keyPair.publicKey), + signature: serializeTaprootSignature( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + leafHash: h.leafHash, + })); + if (tapKeySig) { + this.data.updateInput(inputIndex, { tapKeySig }); + } + if (tapScriptSig.length) { + this.data.updateInput(inputIndex, { tapScriptSig }); + } + return this; + } + signInputAsync(inputIndex, keyPair, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + return this._signInputAsync(inputIndex, keyPair, sighashTypes); + }); + } + signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = checkForInput(this.data.inputs, inputIndex); + if (isTaprootInput(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + }); + } + _signInputAsync( + inputIndex, + keyPair, + sighashTypes = [Transaction.SIGHASH_ALL], + ) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + } + async _signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes = [Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + const signaturePromises = []; + const tapKeyHash = hashesForSig.filter(h => !h.leafHash)[0]; + if (tapKeyHash) { + const tapKeySigPromise = Promise.resolve( + keyPair.signSchnorr(tapKeyHash.hash), + ).then(sig => { + return { tapKeySig: serializeTaprootSignature(sig, input.sighashType) }; + }); + signaturePromises.push(tapKeySigPromise); + } + const tapScriptHashes = hashesForSig.filter(h => !!h.leafHash); + if (tapScriptHashes.length) { + const tapScriptSigPromises = tapScriptHashes.map(tsh => { + return Promise.resolve(keyPair.signSchnorr(tsh.hash)).then( + signature => { + const tapScriptSig = [ + { + pubkey: toXOnly(keyPair.publicKey), + signature: serializeTaprootSignature( + signature, + input.sighashType, + ), + leafHash: tsh.leafHash, + }, + ]; + return { tapScriptSig }; + }, + ); + }); + signaturePromises.push(...tapScriptSigPromises); + } + return Promise.all(signaturePromises).then(results => { + results.forEach(v => this.data.updateInput(inputIndex, v)); + }); + } + checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ) { + if (typeof keyPair.signSchnorr !== 'function') + throw new Error( + `Need Schnorr Signer to sign taproot input #${inputIndex}.`, + ); + const hashesForSig = getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + keyPair.publicKey, + this.__CACHE, + tapLeafHashToSign, + allowedSighashTypes, + ); + if (!hashesForSig || !hashesForSig.length) + throw new Error( + `Can not sign for input #${inputIndex} with the key ${tools.toHex(keyPair.publicKey)}`, + ); + return hashesForSig; + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + checkTaprootInputFields( + this.data.inputs[inputIndex], + updateData, + 'updateInput', + ); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + const outputData = this.data.outputs[outputIndex]; + checkTaprootOutputFields(outputData, updateData, 'updateOutput'); + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } +} +/** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ +const transactionFromBuffer = buffer => new PsbtTransaction(buffer); +/** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ +class PsbtTransaction { + tx; + constructor(buffer = Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!(input.hash instanceof Uint8Array) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? reverseBuffer(tools.fromHex(input.hash)) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !(output.script instanceof Uint8Array) || + typeof output.value !== 'bigint' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } +} +function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } +} +function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } +} +function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = compressPubkey(pkey); + return partialSig.find( + pSig => tools.compare(pSig.pubkey, pubkey) === 0, + ); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; +} +function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; +} +function bip32DerivationIsMine(root) { + return d => { + if (tools.compare(root.fingerprint, d.masterFingerprint)) return false; + if (tools.compare(root.derivePath(d.path).publicKey, d.pubkey)) + return false; + return true; + }; +} +function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } +} +function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } +} +function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + const throws = isTaprootInput(input) + ? checkTaprootInputForSigs(input, action) + : checkInputForSig(input, action); + if (throws) + throw new Error('Can not modify transaction, signatures exist.'); + }); +} +function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); +} +function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${tools.toHex(pubkey)}`, + ); + } +} +function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } +} +function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); +} +function checkTxInputCache(cache, input) { + const key = + tools.toHex(reverseBuffer(Uint8Array.from(input.hash))) + ':' + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; +} +function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (tools.compare(scriptPubKey, redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; +} +const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script'); +const checkWitnessScript = scriptCheckerFactory( + payments.p2wsh, + 'Witness script', +); +function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; +} +function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); +} +function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, +) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; +} +function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, +) { + const input = checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; +} +function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = input.sighashType || Transaction.SIGHASH_ALL; + checkSighashTypeAllowed(sighashType, sighashTypes); + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (tools.compare(prevoutHash, utxoHash) !== 0) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments.p2pkh({ + hash: meaningfulScript.slice(2), + }).output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${tools.toHex(meaningfulScript)}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + "to trick you into paying large fees. This behavior is the same as Psbt's predecessor " + + '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; +} +function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) { + const allPublicKeys = []; + if (input.tapInternalKey) { + const key = getPrevoutTaprootKey(inputIndex, input, cache); + if (key) { + allPublicKeys.push(key); + } + } + if (input.tapScriptSig) { + const tapScriptPubkeys = input.tapScriptSig.map(tss => tss.pubkey); + allPublicKeys.push(...tapScriptPubkeys); + } + const allHashes = allPublicKeys.map(publicKey => + getTaprootHashesForSig(inputIndex, input, inputs, publicKey, cache), + ); + return allHashes.flat(); +} +function getPrevoutTaprootKey(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return isP2TR(script) ? script.subarray(2, 34) : null; +} +function trimTaprootSig(signature) { + return signature.length === 64 ? signature : signature.subarray(0, 64); +} +function getTaprootHashesForSig( + inputIndex, + input, + inputs, + pubkey, + cache, + tapLeafHashToSign, + allowedSighashTypes, +) { + const unsignedTx = cache.__TX; + const sighashType = input.sighashType || Transaction.SIGHASH_DEFAULT; + checkSighashTypeAllowed(sighashType, allowedSighashTypes); + const prevOuts = inputs.map((i, index) => + getScriptAndAmountFromUtxo(index, i, cache), + ); + const signingScripts = prevOuts.map(o => o.script); + const values = prevOuts.map(o => o.value); + const hashes = []; + if (input.tapInternalKey && !tapLeafHashToSign) { + const outputKey = + getPrevoutTaprootKey(inputIndex, input, cache) || Uint8Array.from([]); + if (tools.compare(toXOnly(pubkey), outputKey) === 0) { + const tapKeyHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + sighashType, + ); + hashes.push({ pubkey, hash: tapKeyHash }); + } + } + const tapLeafHashes = (input.tapLeafScript || []) + .filter(tapLeaf => pubkeyInScript(pubkey, tapLeaf.script)) + .map(tapLeaf => { + const hash = tapleafHash({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return Object.assign({ hash }, tapLeaf); + }) + .filter( + tapLeaf => + !tapLeafHashToSign || + tools.compare(tapLeafHashToSign, tapLeaf.hash) === 0, + ) + .map(tapLeaf => { + const tapScriptHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + sighashType, + tapLeaf.hash, + ); + return { + pubkey, + hash: tapScriptHash, + leafHash: tapLeaf.hash, + }; + }); + return hashes.concat(tapLeafHashes); +} +function checkSighashTypeAllowed(sighashType, sighashTypes) { + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } +} +function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; +} +function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; +} +function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (tools.compare(bipDv.masterFingerprint, hdKeyPair.fingerprint) === 0) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (tools.compare(bipDv.pubkey, node.publicKey) !== 0) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; +} +function getSortedSigs(script, partialSig) { + const p2ms = payments.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return tools.compare(ps.pubkey, pk) === 0; + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); +} +function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.encodingLength(vi.bigintValue); + return vi.numberValue; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); +} +function sighashTypeToString(sighashType) { + let text = + sighashType & Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; +} +function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); +} +function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0n; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0n); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(Number(fee / BigInt(bytes))); +} +function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; +} +function getScriptFromUtxo(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return script; +} +function getScriptAndAmountFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return { + script: input.witnessUtxo.script, + value: input.witnessUtxo.value, + }; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const o = nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index]; + return { script: o.script, value: o.value }; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } +} +function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); +} +function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); +} +function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !(lastItem instanceof Uint8Array) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function compressPubkey(pubkey) { + if (pubkey.length === 65) { + const parity = pubkey[64] & 1; + const newKey = pubkey.slice(0, 33); + newKey[0] = 2 | parity; + return newKey; + } + return pubkey.slice(); +} +function isPubkeyLike(buf) { + return buf.length === 33 && bscript.isCanonicalPubKey(buf); +} +function isSigLike(buf) { + return bscript.isCanonicalScriptSignature(buf); +} +function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, +) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; +} +function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } +} +function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; +} +function range(n) { + return [...Array(n).keys()]; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/bip371.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/bip371.js new file mode 100644 index 0000000..7f318aa --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/bip371.js @@ -0,0 +1,490 @@ +import { isTapleaf, isTaptree } from '../types.js'; +import { Transaction } from '../transaction.js'; +import { + witnessStackToScriptWitness, + pubkeyPositionInScript, + isP2TR, +} from './psbtutils.js'; +import { + tweakKey, + tapleafHash, + rootHashFromPath, + LEAF_VERSION_TAPSCRIPT, + MAX_TAPTREE_DEPTH, +} from '../payments/bip341.js'; +import { p2tr } from '../payments/index.js'; +import * as tools from 'uint8array-tools'; +import { signatureBlocksAction } from './psbtutils.js'; +/** + * Converts a public key to an X-only public key. + * @param pubKey The public key to convert. + * @returns The X-only public key. + */ +export const toXOnly = pubKey => + pubKey.length === 32 ? pubKey : pubKey.slice(1, 33); +/** + * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided. + * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path. + * @param inputIndex the position of the PSBT input. + * @param input the PSBT input. + * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash + * and will try to build the finalScriptWitness. + * @returns the finalScriptWitness or throws an exception if no tapleaf found. + */ +export function tapScriptFinalizer(inputIndex, input, tapLeafHashToFinalize) { + const tapLeaf = findTapLeafToFinalize( + input, + inputIndex, + tapLeafHashToFinalize, + ); + try { + const sigs = sortSignatures(input, tapLeaf); + const witness = sigs.concat(tapLeaf.script).concat(tapLeaf.controlBlock); + return { finalScriptWitness: witnessStackToScriptWitness(witness) }; + } catch (err) { + throw new Error(`Can not finalize taproot input #${inputIndex}: ${err}`); + } +} +/** + * Serializes a taproot signature. + * @param sig The signature to serialize. + * @param sighashType The sighash type. Optional. + * @returns The serialized taproot signature. + */ +export function serializeTaprootSignature(sig, sighashType) { + const sighashTypeByte = sighashType + ? Uint8Array.from([sighashType]) + : Uint8Array.from([]); + return tools.concat([sig, sighashTypeByte]); +} +/** + * Checks if a PSBT input is a taproot input. + * @param input The PSBT input to check. + * @returns True if the input is a taproot input, false otherwise. + */ +export function isTaprootInput(input) { + return ( + input && + !!( + input.tapInternalKey || + input.tapMerkleRoot || + (input.tapLeafScript && input.tapLeafScript.length) || + (input.tapBip32Derivation && input.tapBip32Derivation.length) || + (input.witnessUtxo && isP2TR(input.witnessUtxo.script)) + ) + ); +} +/** + * Checks if a PSBT output is a taproot output. + * @param output The PSBT output to check. + * @param script The script to check. Optional. + * @returns True if the output is a taproot output, false otherwise. + */ +export function isTaprootOutput(output, script) { + return ( + output && + !!( + output.tapInternalKey || + output.tapTree || + (output.tapBip32Derivation && output.tapBip32Derivation.length) || + (script && isP2TR(script)) + ) + ); +} +/** + * Checks the taproot input fields for consistency. + * @param inputData The original input data. + * @param newInputData The new input data. + * @param action The action being performed. + * @throws Throws an error if the input fields are inconsistent. + */ +export function checkTaprootInputFields(inputData, newInputData, action) { + checkMixedTaprootAndNonTaprootInputFields(inputData, newInputData, action); + checkIfTapLeafInTree(inputData, newInputData, action); +} +/** + * Checks the taproot output fields for consistency. + * @param outputData The original output data. + * @param newOutputData The new output data. + * @param action The action being performed. + * @throws Throws an error if the output fields are inconsistent. + */ +export function checkTaprootOutputFields(outputData, newOutputData, action) { + checkMixedTaprootAndNonTaprootOutputFields(outputData, newOutputData, action); + checkTaprootScriptPubkey(outputData, newOutputData); +} +function checkTaprootScriptPubkey(outputData, newOutputData) { + if (!newOutputData.tapTree && !newOutputData.tapInternalKey) return; + const tapInternalKey = + newOutputData.tapInternalKey || outputData.tapInternalKey; + const tapTree = newOutputData.tapTree || outputData.tapTree; + if (tapInternalKey) { + const { script: scriptPubkey } = outputData; + const script = getTaprootScripPubkey(tapInternalKey, tapTree); + if (scriptPubkey && tools.compare(script, scriptPubkey) !== 0) + throw new Error('Error adding output. Script or address mismatch.'); + } +} +/** + * Returns the Taproot script public key. + * + * @param tapInternalKey - The Taproot internal key. + * @param tapTree - The Taproot tree (optional). + * @returns The Taproot script public key. + */ +function getTaprootScripPubkey(tapInternalKey, tapTree) { + const scriptTree = tapTree && tapTreeFromList(tapTree.leaves); + const { output } = p2tr({ + internalPubkey: tapInternalKey, + scriptTree, + }); + return output; +} +/** + * Tweak the internal public key for a specific input. + * @param inputIndex - The index of the input. + * @param input - The PsbtInput object representing the input. + * @returns The tweaked internal public key. + * @throws Error if the tap internal key cannot be tweaked. + */ +export function tweakInternalPubKey(inputIndex, input) { + const tapInternalKey = input.tapInternalKey; + const outputKey = + tapInternalKey && tweakKey(tapInternalKey, input.tapMerkleRoot); + if (!outputKey) + throw new Error( + `Cannot tweak tap internal key for input #${inputIndex}. Public key: ${ + // tapInternalKey && tapInternalKey.toString('hex') + tapInternalKey && tools.toHex(tapInternalKey) + }`, + ); + return outputKey.x; +} +/** + * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @param tree the binary tap tree + * @returns a list of BIP 371 tapleaves + */ +export function tapTreeToList(tree) { + if (!isTaptree(tree)) + throw new Error( + 'Cannot convert taptree to tapleaf list. Expecting a tapree structure.', + ); + return _tapTreeToList(tree); +} +/** + * Convert a BIP371 TapLeaf list to a TapTree (binary). + * @param leaves a list of tapleaves where each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed + */ +export function tapTreeFromList(leaves = []) { + if (leaves.length === 1 && leaves[0].depth === 0) + return { + output: leaves[0].script, + version: leaves[0].leafVersion, + }; + return instertLeavesInTree(leaves); +} +/** + * Checks the taproot input for signatures. + * @param input The PSBT input to check. + * @param action The action being performed. + * @returns True if the input has taproot signatures, false otherwise. + */ +export function checkTaprootInputForSigs(input, action) { + const sigs = extractTaprootSigs(input); + return sigs.some(sig => + signatureBlocksAction(sig, decodeSchnorrSignature, action), + ); +} +/** + * Decodes a Schnorr signature. + * @param signature The signature to decode. + * @returns The decoded Schnorr signature. + */ +function decodeSchnorrSignature(signature) { + return { + signature: signature.slice(0, 64), + hashType: signature.slice(64)[0] || Transaction.SIGHASH_DEFAULT, + }; +} +/** + * Extracts taproot signatures from a PSBT input. + * @param input The PSBT input to extract signatures from. + * @returns An array of taproot signatures. + */ +function extractTaprootSigs(input) { + const sigs = []; + if (input.tapKeySig) sigs.push(input.tapKeySig); + if (input.tapScriptSig) + sigs.push(...input.tapScriptSig.map(s => s.signature)); + if (!sigs.length) { + const finalTapKeySig = getTapKeySigFromWithness(input.finalScriptWitness); + if (finalTapKeySig) sigs.push(finalTapKeySig); + } + return sigs; +} +/** + * Gets the taproot signature from the witness. + * @param finalScriptWitness The final script witness. + * @returns The taproot signature, or undefined if not found. + */ +function getTapKeySigFromWithness(finalScriptWitness) { + if (!finalScriptWitness) return; + const witness = finalScriptWitness.slice(2); + // todo: add schnorr signature validation + if (witness.length === 64 || witness.length === 65) return witness; +} +/** + * Converts a binary tree to a BIP371 type list. + * @param tree The binary tap tree. + * @param leaves A list of tapleaves. Optional. + * @param depth The current depth. Optional. + * @returns A list of BIP 371 tapleaves. + * @throws Throws an error if the taptree cannot be converted to a tapleaf list. + */ +function _tapTreeToList(tree, leaves = [], depth = 0) { + if (depth > MAX_TAPTREE_DEPTH) throw new Error('Max taptree depth exceeded.'); + if (!tree) return []; + if (isTapleaf(tree)) { + leaves.push({ + depth, + leafVersion: tree.version || LEAF_VERSION_TAPSCRIPT, + script: tree.output, + }); + return leaves; + } + if (tree[0]) _tapTreeToList(tree[0], leaves, depth + 1); + if (tree[1]) _tapTreeToList(tree[1], leaves, depth + 1); + return leaves; +} +/** + * Inserts the tapleaves into the taproot tree. + * @param leaves The tapleaves to insert. + * @returns The taproot tree. + * @throws Throws an error if there is no room left to insert a tapleaf in the tree. + */ +function instertLeavesInTree(leaves) { + let tree; + for (const leaf of leaves) { + tree = instertLeafInTree(leaf, tree); + if (!tree) throw new Error(`No room left to insert tapleaf in tree`); + } + return tree; +} +/** + * Inserts a tapleaf into the taproot tree. + * @param leaf The tapleaf to insert. + * @param tree The taproot tree. + * @param depth The current depth. Optional. + * @returns The updated taproot tree. + */ +function instertLeafInTree(leaf, tree, depth = 0) { + if (depth > MAX_TAPTREE_DEPTH) throw new Error('Max taptree depth exceeded.'); + if (leaf.depth === depth) { + if (!tree) + return { + output: leaf.script, + version: leaf.leafVersion, + }; + return; + } + if (isTapleaf(tree)) return; + const leftSide = instertLeafInTree(leaf, tree && tree[0], depth + 1); + if (leftSide) return [leftSide, tree && tree[1]]; + const rightSide = instertLeafInTree(leaf, tree && tree[1], depth + 1); + if (rightSide) return [tree && tree[0], rightSide]; +} +/** + * Checks the input fields for mixed taproot and non-taproot fields. + * @param inputData The original input data. + * @param newInputData The new input data. + * @param action The action being performed. + * @throws Throws an error if the input fields are inconsistent. + */ +function checkMixedTaprootAndNonTaprootInputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootInput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootInput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootInput(newInputData) && + hasNonTaprootFields(newInputData); // todo: bad? use !=== + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +/** + * Checks the output fields for mixed taproot and non-taproot fields. + * @param inputData The original output data. + * @param newInputData The new output data. + * @param action The action being performed. + * @throws Throws an error if the output fields are inconsistent. + */ +function checkMixedTaprootAndNonTaprootOutputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootOutput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootOutput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootOutput(newInputData) && + hasNonTaprootFields(newInputData); + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +/** + * Checks if the tap leaf is part of the tap tree for the given input data. + * Throws an error if the tap leaf is not part of the tap tree. + * @param inputData - The original PsbtInput data. + * @param newInputData - The new PsbtInput data. + * @param action - The action being performed. + * @throws {Error} - If the tap leaf is not part of the tap tree. + */ +function checkIfTapLeafInTree(inputData, newInputData, action) { + if (newInputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + const oldLeafsInTree = (inputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + if (!newLeafsInTree || !oldLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } else if (inputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, inputData.tapMerkleRoot), + ); + if (!newLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } +} +/** + * Checks if a TapLeafScript is present in a Merkle tree. + * @param tapLeaf The TapLeafScript to check. + * @param merkleRoot The Merkle root of the tree. If not provided, the function assumes the TapLeafScript is present. + * @returns A boolean indicating whether the TapLeafScript is present in the tree. + */ +function isTapLeafInTree(tapLeaf, merkleRoot) { + if (!merkleRoot) return true; + const leafHash = tapleafHash({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + const rootHash = rootHashFromPath(tapLeaf.controlBlock, leafHash); + return tools.compare(rootHash, merkleRoot) === 0; +} +/** + * Sorts the signatures in the input's tapScriptSig array based on their position in the tapLeaf script. + * + * @param input - The PsbtInput object. + * @param tapLeaf - The TapLeafScript object. + * @returns An array of sorted signatures as Buffers. + */ +function sortSignatures(input, tapLeaf) { + const leafHash = tapleafHash({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return ( + (input.tapScriptSig || []) + // .filter(tss => tss.leafHash.equals(leafHash)) + .filter(tss => tools.compare(tss.leafHash, leafHash) === 0) + .map(tss => addPubkeyPositionInScript(tapLeaf.script, tss)) + .sort((t1, t2) => t2.positionInScript - t1.positionInScript) + .map(t => t.signature) + ); +} +/** + * Adds the position of a public key in a script to a TapScriptSig object. + * @param script The script in which to find the position of the public key. + * @param tss The TapScriptSig object to add the position to. + * @returns A TapScriptSigWitPosition object with the added position. + */ +function addPubkeyPositionInScript(script, tss) { + return Object.assign( + { + positionInScript: pubkeyPositionInScript(tss.pubkey, script), + }, + tss, + ); +} +/** + * Find tapleaf by hash, or get the signed tapleaf with the shortest path. + */ +function findTapLeafToFinalize(input, inputIndex, leafHashToFinalize) { + if (!input.tapScriptSig || !input.tapScriptSig.length) + throw new Error( + `Can not finalize taproot input #${inputIndex}. No tapleaf script signature provided.`, + ); + const tapLeaf = (input.tapLeafScript || []) + .sort((a, b) => a.controlBlock.length - b.controlBlock.length) + .find(leaf => + canFinalizeLeaf(leaf, input.tapScriptSig, leafHashToFinalize), + ); + if (!tapLeaf) + throw new Error( + `Can not finalize taproot input #${inputIndex}. Signature for tapleaf script not found.`, + ); + return tapLeaf; +} +/** + * Determines whether a TapLeafScript can be finalized. + * + * @param leaf - The TapLeafScript to check. + * @param tapScriptSig - The array of TapScriptSig objects. + * @param hash - The optional hash to compare with the leaf hash. + * @returns A boolean indicating whether the TapLeafScript can be finalized. + */ +function canFinalizeLeaf(leaf, tapScriptSig, hash) { + const leafHash = tapleafHash({ + output: leaf.script, + version: leaf.leafVersion, + }); + const whiteListedHash = !hash || tools.compare(leafHash, hash) === 0; + return ( + whiteListedHash && + tapScriptSig.find(tss => tools.compare(tss.leafHash, leafHash) === 0) !== + undefined + ); +} +/** + * Checks if the given PsbtInput or PsbtOutput has non-taproot fields. + * Non-taproot fields include redeemScript, witnessScript, and bip32Derivation. + * @param io The PsbtInput or PsbtOutput to check. + * @returns A boolean indicating whether the given input or output has non-taproot fields. + */ +function hasNonTaprootFields(io) { + return ( + io && + !!( + io.redeemScript || + io.witnessScript || + (io.bip32Derivation && io.bip32Derivation.length) + ) + ); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/psbtutils.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/psbtutils.js new file mode 100644 index 0000000..fa4bc27 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/psbt/psbtutils.js @@ -0,0 +1,168 @@ +import * as varuint from 'varuint-bitcoin'; +import * as bscript from '../script.js'; +import { Transaction } from '../transaction.js'; +import { hash160 } from '../crypto.js'; +import * as payments from '../payments/index.js'; +import * as tools from 'uint8array-tools'; +/** + * Checks if a given payment factory can generate a payment script from a given script. + * @param payment The payment factory to check. + * @returns A function that takes a script and returns a boolean indicating whether the payment factory can generate a payment script from the script. + */ +function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; +} +export const isP2MS = isPaymentFactory(payments.p2ms); +export const isP2PK = isPaymentFactory(payments.p2pk); +export const isP2PKH = isPaymentFactory(payments.p2pkh); +export const isP2WPKH = isPaymentFactory(payments.p2wpkh); +export const isP2WSHScript = isPaymentFactory(payments.p2wsh); +export const isP2SHScript = isPaymentFactory(payments.p2sh); +export const isP2TR = isPaymentFactory(payments.p2tr); +/** + * Converts a witness stack to a script witness. + * @param witness The witness stack to convert. + * @returns The script witness as a Buffer. + */ +export function witnessStackToScriptWitness(witness) { + let buffer = new Uint8Array(0); + function writeSlice(slice) { + buffer = tools.concat([buffer, slice]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = tools.concat([buffer, new Uint8Array(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; +} +/** + * Finds the position of a public key in a script. + * @param pubkey The public key to search for. + * @param script The script to search in. + * @returns The index of the public key in the script, or -1 if not found. + * @throws {Error} If there is an unknown script error. + */ +export function pubkeyPositionInScript(pubkey, script) { + const pubkeyHash = hash160(pubkey); + const pubkeyXOnly = pubkey.slice(1, 33); // slice before calling? + const decompiled = bscript.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.findIndex(element => { + if (typeof element === 'number') return false; + return ( + tools.compare(pubkey, element) === 0 || + tools.compare(pubkeyHash, element) === 0 || + tools.compare(pubkeyXOnly, element) === 0 + ); + }); +} +/** + * Checks if a public key is present in a script. + * @param pubkey The public key to check. + * @param script The script to search in. + * @returns A boolean indicating whether the public key is present in the script. + */ +export function pubkeyInScript(pubkey, script) { + return pubkeyPositionInScript(pubkey, script) !== -1; +} +/** + * Checks if an input contains a signature for a specific action. + * @param input - The input to check. + * @param action - The action to check for. + * @returns A boolean indicating whether the input contains a signature for the specified action. + */ +export function checkInputForSig(input, action) { + const pSigs = extractPartialSigs(input); + return pSigs.some(pSig => + signatureBlocksAction(pSig, bscript.signature.decode, action), + ); +} +/** + * Determines if a given action is allowed for a signature block. + * @param signature - The signature block. + * @param signatureDecodeFn - The function used to decode the signature. + * @param action - The action to be checked. + * @returns True if the action is allowed, false otherwise. + */ +export function signatureBlocksAction(signature, signatureDecodeFn, action) { + const { hashType } = signatureDecodeFn(signature); + const whitelist = []; + const isAnyoneCanPay = hashType & Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case Transaction.SIGHASH_ALL: + break; + case Transaction.SIGHASH_SINGLE: + case Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + return true; + } + return false; +} +/** + * Extracts the signatures from a PsbtInput object. + * If the input has partial signatures, it returns an array of the signatures. + * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness. + * If it does, it extracts the signatures from the final scripts and returns them. + * If none of the above conditions are met, it returns an empty array. + * + * @param input - The PsbtInput object from which to extract the signatures. + * @returns An array of signatures extracted from the PsbtInput object. + */ +function extractPartialSigs(input) { + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return []; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + return pSigs.map(p => p.signature); +} +/** + * Retrieves the partial signatures (Psigs) from the input's final scripts. + * Psigs are extracted from both the final scriptSig and final scriptWitness of the input. + * Only canonical script signatures are considered. + * + * @param input - The PsbtInput object representing the input. + * @returns An array of PartialSig objects containing the extracted Psigs. + */ +function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return ( + item instanceof Uint8Array && bscript.isCanonicalScriptSignature(item) + ); + }) + .map(sig => ({ signature: sig })); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/push_data.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/push_data.js new file mode 100644 index 0000000..12b233a --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/push_data.js @@ -0,0 +1,77 @@ +import { OPS } from './ops.js'; +import * as tools from 'uint8array-tools'; +/** + * Calculates the encoding length of a number used for push data in Bitcoin transactions. + * @param i The number to calculate the encoding length for. + * @returns The encoding length of the number. + */ +export function encodingLength(i) { + return i < OPS.OP_PUSHDATA1 ? 1 : i <= 0xff ? 2 : i <= 0xffff ? 3 : 5; +} +/** + * Encodes a number into a buffer using a variable-length encoding scheme. + * The encoded buffer is written starting at the specified offset. + * Returns the size of the encoded buffer. + * + * @param buffer - The buffer to write the encoded data into. + * @param num - The number to encode. + * @param offset - The offset at which to start writing the encoded buffer. + * @returns The size of the encoded buffer. + */ +export function encode(buffer, num, offset) { + const size = encodingLength(num); + // ~6 bit + if (size === 1) { + tools.writeUInt8(buffer, offset, num); + // 8 bit + } else if (size === 2) { + tools.writeUInt8(buffer, offset, OPS.OP_PUSHDATA1); + tools.writeUInt8(buffer, offset + 1, num); + // 16 bit + } else if (size === 3) { + tools.writeUInt8(buffer, offset, OPS.OP_PUSHDATA2); + tools.writeUInt16(buffer, offset + 1, num, 'LE'); + // 32 bit + } else { + tools.writeUInt8(buffer, offset, OPS.OP_PUSHDATA4); + tools.writeUInt32(buffer, offset + 1, num, 'LE'); + } + return size; +} +/** + * Decodes a buffer and returns information about the opcode, number, and size. + * @param buffer - The buffer to decode. + * @param offset - The offset within the buffer to start decoding. + * @returns An object containing the opcode, number, and size, or null if decoding fails. + */ +export function decode(buffer, offset) { + const opcode = tools.readUInt8(buffer, offset); + let num; + let size; + // ~6 bit + if (opcode < OPS.OP_PUSHDATA1) { + num = opcode; + size = 1; + // 8 bit + } else if (opcode === OPS.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null; + num = tools.readUInt8(buffer, offset + 1); + size = 2; + // 16 bit + } else if (opcode === OPS.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null; + num = tools.readUInt16(buffer, offset + 1, 'LE'); + size = 3; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null; + if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode'); + num = tools.readUInt32(buffer, offset + 1, 'LE'); + size = 5; + } + return { + opcode, + number: num, + size, + }; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script.js new file mode 100644 index 0000000..985d016 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script.js @@ -0,0 +1,199 @@ +/** + * Script tools, including decompile, compile, toASM, fromASM, toStack, isCanonicalPubKey, isCanonicalScriptSignature + * @packageDocumentation + */ +import * as bip66 from './bip66.js'; +import { OPS, REVERSE_OPS } from './ops.js'; +import * as pushdata from './push_data.js'; +import * as scriptNumber from './script_number.js'; +import * as scriptSignature from './script_signature.js'; +import * as types from './types.js'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1 +export { OPS }; +const StackSchema = v.array(v.union([v.instance(Uint8Array), v.number()])); +function isOPInt(value) { + return ( + v.is(v.number(), value) && + (value === OPS.OP_0 || + (value >= OPS.OP_1 && value <= OPS.OP_16) || + value === OPS.OP_1NEGATE) + ); +} +function isPushOnlyChunk(value) { + return v.is(types.BufferSchema, value) || isOPInt(value); +} +export function isPushOnly(value) { + return v.is(v.pipe(v.any(), v.everyItem(isPushOnlyChunk)), value); +} +export function countNonPushOnlyOPs(value) { + return value.length - value.filter(isPushOnlyChunk).length; +} +function asMinimalOP(buffer) { + if (buffer.length === 0) return OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return OPS.OP_1NEGATE; +} +function chunksIsBuffer(buf) { + return buf instanceof Uint8Array; +} +function chunksIsArray(buf) { + return v.is(StackSchema, buf); +} +function singleChunkIsBuffer(buf) { + return buf instanceof Uint8Array; +} +/** + * Compiles an array of chunks into a Buffer. + * + * @param chunks - The array of chunks to compile. + * @returns The compiled Buffer. + * @throws Error if the compilation fails. + */ +export function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + v.parse(StackSchema, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = new Uint8Array(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + tools.writeUInt8(buffer, offset, opcode); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + buffer.set(chunk, offset); + offset += chunk.length; + // opcode + } else { + tools.writeUInt8(buffer, offset, chunk); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; +} +export function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + v.parse(types.BufferSchema, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > OPS.OP_0 && opcode <= OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; +} +/** + * Converts the given chunks into an ASM (Assembly) string representation. + * If the chunks parameter is a Buffer, it will be decompiled into a Stack before conversion. + * @param chunks - The chunks to convert into ASM. + * @returns The ASM string representation of the chunks. + */ +export function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + if (!chunks) { + throw new Error('Could not convert invalid chunks to ASM'); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return tools.toHex(chunk); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); +} +/** + * Converts an ASM string to a Buffer. + * @param asm The ASM string to convert. + * @returns The converted Buffer. + */ +export function fromASM(asm) { + v.parse(v.string(), asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (OPS[chunkStr] !== undefined) return OPS[chunkStr]; + v.parse(types.HexSchema, chunkStr); + // data! + return tools.fromHex(chunkStr); + }), + ); +} +/** + * Converts the given chunks into a stack of buffers. + * + * @param chunks - The chunks to convert. + * @returns The stack of buffers. + */ +export function toStack(chunks) { + chunks = decompile(chunks); + v.parse(v.custom(isPushOnly), chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === OPS.OP_0) return new Uint8Array(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); +} +export function isCanonicalPubKey(buffer) { + return types.isPoint(buffer); +} +export function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + return hashTypeMod > 0x00 && hashTypeMod < 0x04; +} +export function isCanonicalScriptSignature(buffer) { + if (!(buffer instanceof Uint8Array)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); +} +export const number = scriptNumber; +export const signature = scriptSignature; diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_number.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_number.js new file mode 100644 index 0000000..b96c869 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_number.js @@ -0,0 +1,74 @@ +import * as tools from 'uint8array-tools'; +/** + * Decodes a script number from a buffer. + * + * @param buffer - The buffer containing the script number. + * @param maxLength - The maximum length of the script number. Defaults to 4. + * @param minimal - Whether the script number should be minimal. Defaults to true. + * @returns The decoded script number. + * @throws {TypeError} If the script number overflows the maximum length. + * @throws {Error} If the script number is not minimally encoded when minimal is true. + */ +export function decode(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = tools.readUInt32(buffer, 0, 'LE'); + const b = tools.readUInt8(buffer, 4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; +} +function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; +} +/** + * Encodes a number into a Uint8Array using a specific format. + * + * @param _number - The number to encode. + * @returns The encoded number as a Uint8Array. + */ +export function encode(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = new Uint8Array(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + tools.writeUInt8(buffer, i, value & 0xff); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + tools.writeUInt8(buffer, size - 1, negative ? 0x80 : 0x00); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_signature.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_signature.js new file mode 100644 index 0000000..fbf3f95 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/script_signature.js @@ -0,0 +1,75 @@ +import * as bip66 from './bip66.js'; +import { isDefinedHashType } from './script.js'; +import * as v from 'valibot'; +import * as tools from 'uint8array-tools'; +import { NBufferSchemaFactory, UInt8Schema } from './types.js'; +const ZERO = new Uint8Array(1); +/** + * Converts a buffer to a DER-encoded buffer. + * @param x - The buffer to be converted. + * @returns The DER-encoded buffer. + */ +function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO; + x = x.slice(i); + if (x[0] & 0x80) return tools.concat([ZERO, x]); + return x; +} +/** + * Converts a DER-encoded signature to a buffer. + * If the first byte of the input buffer is 0x00, it is skipped. + * The resulting buffer is 32 bytes long, filled with zeros if necessary. + * @param x - The DER-encoded signature. + * @returns The converted buffer. + */ +function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = new Uint8Array(32); + const bstart = Math.max(0, 32 - x.length); + buffer.set(x, bstart); + return buffer; +} +// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) +/** + * Decodes a buffer into a ScriptSignature object. + * @param buffer - The buffer to decode. + * @returns The decoded ScriptSignature object. + * @throws Error if the hashType is invalid. + */ +export function decode(buffer) { + const hashType = tools.readUInt8(buffer, buffer.length - 1); + if (!isDefinedHashType(hashType)) { + throw new Error('Invalid hashType ' + hashType); + } + const decoded = bip66.decode(buffer.subarray(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = tools.concat([r, s]); + return { signature, hashType }; +} +/** + * Encodes a signature and hash type into a buffer. + * @param signature - The signature to encode. + * @param hashType - The hash type to encode. + * @returns The encoded buffer. + * @throws Error if the hashType is invalid. + */ +export function encode(signature, hashType) { + v.parse( + v.object({ + signature: NBufferSchemaFactory(64), + hashType: UInt8Schema, + }), + { signature, hashType }, + ); + if (!isDefinedHashType(hashType)) { + throw new Error('Invalid hashType ' + hashType); + } + const hashTypeBuffer = new Uint8Array(1); + tools.writeUInt8(hashTypeBuffer, 0, hashType); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return tools.concat([bip66.encode(r, s), hashTypeBuffer]); +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/transaction.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/transaction.js new file mode 100644 index 0000000..3379e0c --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/transaction.js @@ -0,0 +1,545 @@ +import { + BufferReader, + BufferWriter, + reverseBuffer, + varuint, +} from './bufferutils.js'; +import * as bcrypto from './crypto.js'; +import { sha256 } from '@noble/hashes/sha256'; +import * as bscript from './script.js'; +import { OPS as opcodes } from './script.js'; +import * as types from './types.js'; +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +function varSliceSize(someScript) { + const length = someScript.length; + return varuint.encodingLength(length) + length; +} +function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); +} +const EMPTY_BUFFER = new Uint8Array(0); +const EMPTY_WITNESS = []; +const ZERO = tools.fromHex( + '0000000000000000000000000000000000000000000000000000000000000000', +); +const ONE = tools.fromHex( + '0000000000000000000000000000000000000000000000000000000000000001', +); +const VALUE_UINT64_MAX = tools.fromHex('ffffffffffffffff'); +const BLANK_OUTPUT = { + script: EMPTY_BUFFER, + valueBuffer: VALUE_UINT64_MAX, +}; +function isOutput(out) { + return out.value !== undefined; +} +/** + * Represents a Bitcoin transaction. + */ +export class Transaction { + static DEFAULT_SEQUENCE = 0xffffffff; + static SIGHASH_DEFAULT = 0x00; + static SIGHASH_ALL = 0x01; + static SIGHASH_NONE = 0x02; + static SIGHASH_SINGLE = 0x03; + static SIGHASH_ANYONECANPAY = 0x80; + static SIGHASH_OUTPUT_MASK = 0x03; + static SIGHASH_INPUT_MASK = 0x80; + static ADVANCED_TRANSACTION_MARKER = 0x00; + static ADVANCED_TRANSACTION_FLAG = 0x01; + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(tools.fromHex(hex), false); + } + static isCoinbaseHash(buffer) { + v.parse(types.Hash256bitSchema, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + version = 1; + locktime = 0; + ins = []; + outs = []; + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + v.parse( + v.tuple([ + types.Hash256bitSchema, + types.UInt32Schema, + v.nullable(v.optional(types.UInt32Schema)), + v.nullable(v.optional(types.BufferSchema)), + ]), + [hash, index, sequence, scriptSig], + ); + if (sequence === undefined || sequence === null) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_BUFFER, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + v.parse(v.tuple([types.BufferSchema, types.SatoshiSchema]), [ + scriptPubKey, + value, + ]); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint.encodingLength(this.ins.length) + + varuint.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + v.parse(v.tuple([types.UInt32Schema, types.BufferSchema, v.number()]), [ + inIndex, + prevOutScript, + hashType, + ]); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript.compile( + bscript.decompile(prevOutScript).filter(x => { + return x !== opcodes.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_BUFFER; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = new Uint8Array(txTmp.byteLength(false) + 4); + tools.writeInt32(buffer, buffer.length - 4, hashType, 'LE'); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto.hash256(buffer); + } + hashForWitnessV1(inIndex, prevOutScripts, values, hashType, leafHash, annex) { + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#common-signature-message + v.parse( + v.tuple([ + types.UInt32Schema, + v.array(types.BufferSchema), + v.array(types.SatoshiSchema), + types.UInt32Schema, + ]), + [inIndex, prevOutScripts, values, hashType], + ); + if ( + values.length !== this.ins.length || + prevOutScripts.length !== this.ins.length + ) { + throw new Error('Must supply prevout script and value for all inputs'); + } + const outputType = + hashType === Transaction.SIGHASH_DEFAULT + ? Transaction.SIGHASH_ALL + : hashType & Transaction.SIGHASH_OUTPUT_MASK; + const inputType = hashType & Transaction.SIGHASH_INPUT_MASK; + const isAnyoneCanPay = inputType === Transaction.SIGHASH_ANYONECANPAY; + const isNone = outputType === Transaction.SIGHASH_NONE; + const isSingle = outputType === Transaction.SIGHASH_SINGLE; + let hashPrevouts = EMPTY_BUFFER; + let hashAmounts = EMPTY_BUFFER; + let hashScriptPubKeys = EMPTY_BUFFER; + let hashSequences = EMPTY_BUFFER; + let hashOutputs = EMPTY_BUFFER; + if (!isAnyoneCanPay) { + let bufferWriter = BufferWriter.withCapacity(36 * this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = sha256(bufferWriter.end()); + bufferWriter = BufferWriter.withCapacity(8 * this.ins.length); + values.forEach(value => bufferWriter.writeInt64(value)); + hashAmounts = sha256(bufferWriter.end()); + bufferWriter = BufferWriter.withCapacity( + prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), + ); + prevOutScripts.forEach(prevOutScript => + bufferWriter.writeVarSlice(prevOutScript), + ); + hashScriptPubKeys = sha256(bufferWriter.end()); + bufferWriter = BufferWriter.withCapacity(4 * this.ins.length); + this.ins.forEach(txIn => bufferWriter.writeUInt32(txIn.sequence)); + hashSequences = sha256(bufferWriter.end()); + } + if (!(isNone || isSingle)) { + if (!this.outs.length) + throw new Error('Add outputs to the transaction before signing.'); + const txOutsSize = this.outs + .map(output => 8 + varSliceSize(output.script)) + .reduce((a, b) => a + b); + const bufferWriter = BufferWriter.withCapacity(txOutsSize); + this.outs.forEach(out => { + bufferWriter.writeInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = sha256(bufferWriter.end()); + } else if (isSingle && inIndex < this.outs.length) { + const output = this.outs[inIndex]; + const bufferWriter = BufferWriter.withCapacity( + 8 + varSliceSize(output.script), + ); + bufferWriter.writeInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = sha256(bufferWriter.end()); + } + const spendType = (leafHash ? 2 : 0) + (annex ? 1 : 0); + // Length calculation from: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-14 + // With extension from: + // https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#signature-validation + const sigMsgSize = + 174 - + (isAnyoneCanPay ? 49 : 0) - + (isNone ? 32 : 0) + + (annex ? 32 : 0) + + (leafHash ? 37 : 0); + const sigMsgWriter = BufferWriter.withCapacity(sigMsgSize); + sigMsgWriter.writeUInt8(hashType); + // Transaction + sigMsgWriter.writeInt32(this.version); + sigMsgWriter.writeUInt32(this.locktime); + sigMsgWriter.writeSlice(hashPrevouts); + sigMsgWriter.writeSlice(hashAmounts); + sigMsgWriter.writeSlice(hashScriptPubKeys); + sigMsgWriter.writeSlice(hashSequences); + if (!(isNone || isSingle)) { + sigMsgWriter.writeSlice(hashOutputs); + } + // Input + sigMsgWriter.writeUInt8(spendType); + if (isAnyoneCanPay) { + const input = this.ins[inIndex]; + sigMsgWriter.writeSlice(input.hash); + sigMsgWriter.writeUInt32(input.index); + sigMsgWriter.writeInt64(values[inIndex]); + sigMsgWriter.writeVarSlice(prevOutScripts[inIndex]); + sigMsgWriter.writeUInt32(input.sequence); + } else { + sigMsgWriter.writeUInt32(inIndex); + } + if (annex) { + const bufferWriter = BufferWriter.withCapacity(varSliceSize(annex)); + bufferWriter.writeVarSlice(annex); + sigMsgWriter.writeSlice(sha256(bufferWriter.end())); + } + // Output + if (isSingle) { + sigMsgWriter.writeSlice(hashOutputs); + } + // BIP342 extension + if (leafHash) { + sigMsgWriter.writeSlice(leafHash); + sigMsgWriter.writeUInt8(0); + sigMsgWriter.writeUInt32(0xffffffff); + } + // Extra zero byte because: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-19 + return bcrypto.taggedHash( + 'TapSighash', + tools.concat([Uint8Array.from([0x00]), sigMsgWriter.end()]), + ); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + v.parse( + v.tuple([ + types.UInt32Schema, + types.BufferSchema, + types.SatoshiSchema, + types.UInt32Schema, + ]), + [inIndex, prevOutScript, value, hashType], + ); + let tbuffer = Uint8Array.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = new Uint8Array(36 * this.ins.length); + bufferWriter = new BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = new Uint8Array(4 * this.ins.length); + bufferWriter = new BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = new Uint8Array(txOutsSize); + bufferWriter = new BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = new Uint8Array(8 + varSliceSize(output.script)); + bufferWriter = new BufferWriter(tbuffer, 0); + bufferWriter.writeInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto.hash256(tbuffer); + } + tbuffer = new Uint8Array(156 + varSliceSize(prevOutScript)); + bufferWriter = new BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return new Uint8Array(32); + return bcrypto.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return tools.toHex(reverseBuffer(this.getHash(false))); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return tools.toHex(this.toBuffer(undefined, undefined)); + } + setInputScript(index, scriptSig) { + v.parse(v.tuple([v.number(), types.BufferSchema]), [index, scriptSig]); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + v.parse(v.tuple([v.number(), v.array(types.BufferSchema)]), [ + index, + witness, + ]); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = new Uint8Array(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new BufferWriter(buffer, initialOffset || 0); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } +} diff --git a/src/libMPC/node_modules/bitcoinjs-lib/src/esm/types.js b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/types.js new file mode 100644 index 0000000..8e406a3 --- /dev/null +++ b/src/libMPC/node_modules/bitcoinjs-lib/src/esm/types.js @@ -0,0 +1,83 @@ +import * as tools from 'uint8array-tools'; +import * as v from 'valibot'; +const ZERO32 = new Uint8Array(32); +const EC_P = tools.fromHex( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', +); +export const NBufferSchemaFactory = size => + v.pipe(v.instance(Uint8Array), v.length(size)); +/** + * Checks if two arrays of Buffers are equal. + * @param a - The first array of Buffers. + * @param b - The second array of Buffers. + * @returns True if the arrays are equal, false otherwise. + */ +export function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return tools.compare(x, b[i]) === 0; + }); +} +/** + * Checks if the given value is a valid elliptic curve point. + * @param p - The value to check. + * @returns True if the value is a valid elliptic curve point, false otherwise. + */ +export function isPoint(p) { + if (!(p instanceof Uint8Array)) return false; + if (p.length < 33) return false; + const t = p[0]; + const x = p.slice(1, 33); + if (tools.compare(ZERO32, x) === 0) return false; + if (tools.compare(x, EC_P) >= 0) return false; + if ((t === 0x02 || t === 0x03) && p.length === 33) { + return true; + } + const y = p.slice(33); + if (tools.compare(ZERO32, y) === 0) return false; + if (tools.compare(y, EC_P) >= 0) return false; + if (t === 0x04 && p.length === 65) return true; + return false; +} +export const TAPLEAF_VERSION_MASK = 0xfe; +export function isTapleaf(o) { + if (!o || !('output' in o)) return false; + if (!(o.output instanceof Uint8Array)) return false; + if (o.version !== undefined) + return (o.version & TAPLEAF_VERSION_MASK) === o.version; + return true; +} +export function isTaptree(scriptTree) { + if (!Array.isArray(scriptTree)) return isTapleaf(scriptTree); + if (scriptTree.length !== 2) return false; + return scriptTree.every(t => isTaptree(t)); +} +export const Buffer256bitSchema = NBufferSchemaFactory(32); +export const Hash160bitSchema = NBufferSchemaFactory(20); +export const Hash256bitSchema = NBufferSchemaFactory(32); +export const BufferSchema = v.instance(Uint8Array); +export const HexSchema = v.pipe(v.string(), v.regex(/^([0-9a-f]{2})+$/i)); +export const UInt8Schema = v.pipe( + v.number(), + v.integer(), + v.minValue(0), + v.maxValue(0xff), +); +export const UInt32Schema = v.pipe( + v.number(), + v.integer(), + v.minValue(0), + v.maxValue(0xffffffff), +); +export const SatoshiSchema = v.pipe( + v.bigint(), + v.minValue(0n), + v.maxValue(0x7fffffffffffffffn), +); +export const NullablePartial = a => + v.object( + Object.entries(a).reduce( + (acc, next) => ({ ...acc, [next[0]]: v.nullish(next[1]) }), + {}, + ), + ); diff --git a/src/libMPC/node_modules/bs58/LICENSE b/src/libMPC/node_modules/bs58/LICENSE new file mode 100644 index 0000000..4d5f7a1 --- /dev/null +++ b/src/libMPC/node_modules/bs58/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 cryptocoinjs + +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. diff --git a/src/libMPC/node_modules/bs58/README.md b/src/libMPC/node_modules/bs58/README.md new file mode 100644 index 0000000..76a4ff0 --- /dev/null +++ b/src/libMPC/node_modules/bs58/README.md @@ -0,0 +1,91 @@ +bs58 +==== + +[![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) + +JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. + +**Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. + + +Install +------- + + npm i --save bs58 + + +API +--- + +### encode(input) + +`input` must be a `Uint8Array`, `Buffer`, or an `Array`. It returns a `string`. + +**example**: + +```js +import bs58 from 'bs58' + +const bytes = Uint8Array.from([ + 0, 60, 23, 110, 101, 155, 234, + 15, 41, 163, 233, 191, 120, 128, + 193, 18, 177, 179, 27, 77, 200, + 38, 38, 129, 135 +]) +const address = bs58.encode(bytes) +console.log(address) +// => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS +``` + + +### decode(input) + +`input` must be a base 58 encoded string. Returns a Uint8Array. + +**example**: + +```js +import bs58 from 'bs58' + +const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' +const bytes = bs58.decode(address) +// See uint8array-tools package for helpful hex encoding/decoding/compare tools +console.log(Buffer.from(bytes).toString('hex')) +// => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 +``` + +Browser +----------- +You can use this module in the browser. Install Browserify: + +```bash +npm install -g browserify +``` + +then run: + +```bash +browserify node_modules/bs58/cjs/index.cjs -o bs58.bundle.js --standalone bs58 +``` + +Hack / Test +----------- + +Uses JavaScript standard style. Read more: + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + + +Credits +------- +- [Mike Hearn](https://github.com/mikehearn) for original Java implementation +- [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript +- [Stephan Pair](https://github.com/gasteve) for buffer improvements +- [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib +- [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency + + +License +------- + +MIT diff --git a/src/libMPC/node_modules/bs58/package.json b/src/libMPC/node_modules/bs58/package.json new file mode 100644 index 0000000..bdc7d2a --- /dev/null +++ b/src/libMPC/node_modules/bs58/package.json @@ -0,0 +1,54 @@ +{ + "name": "bs58", + "version": "6.0.0", + "type": "module", + "description": "Base 58 encoding / decoding", + "keywords": [ + "base58", + "bitcoin", + "crypto", + "crytography", + "decode", + "decoding", + "encode", + "encoding", + "litecoin" + ], + "license": "MIT", + "devDependencies": { + "@types/node": "^20.14.8", + "rimraf": "^5.0.7", + "tape": "^5.3.0", + "ts-standard": "^12.0.2", + "typescript": "^5.5.2" + }, + "repository": { + "url": "https://github.com/cryptocoinjs/bs58", + "type": "git" + }, + "files": [ + "src" + ], + "main": "src/cjs/index.cjs", + "module": "src/esm/index.js", + "types": "src/cjs/index.d.ts", + "exports": { + ".": { + "import": "./src/esm/index.js", + "require": "./src/cjs/index.cjs", + "types": "./src/cjs/index.d.ts" + } + }, + "scripts": { + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json", + "clean": "rimraf src", + "gitdiff": "npm run build && git diff --exit-code", + "postbuild": "find src/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\;", + "standard": "ts-standard --ignore src --ignore test", + "test": "npm run standard && npm run unit", + "unit": "tape test/index.js" + }, + "dependencies": { + "base-x": "^5.0.0" + } +} diff --git a/src/libMPC/node_modules/bs58/src/cjs/index.cjs b/src/libMPC/node_modules/bs58/src/cjs/index.cjs new file mode 100644 index 0000000..0a5d975 --- /dev/null +++ b/src/libMPC/node_modules/bs58/src/cjs/index.cjs @@ -0,0 +1,8 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var base_x_1 = __importDefault(require("base-x")); +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +exports.default = (0, base_x_1.default)(ALPHABET); diff --git a/src/libMPC/node_modules/bs58/src/cjs/index.d.ts b/src/libMPC/node_modules/bs58/src/cjs/index.d.ts new file mode 100644 index 0000000..6aeee88 --- /dev/null +++ b/src/libMPC/node_modules/bs58/src/cjs/index.d.ts @@ -0,0 +1,3 @@ +import basex from 'base-x'; +declare const _default: basex.BaseConverter; +export default _default; diff --git a/src/libMPC/node_modules/bs58/src/esm/index.js b/src/libMPC/node_modules/bs58/src/esm/index.js new file mode 100644 index 0000000..84a71b1 --- /dev/null +++ b/src/libMPC/node_modules/bs58/src/esm/index.js @@ -0,0 +1,3 @@ +import basex from 'base-x'; +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +export default basex(ALPHABET); diff --git a/src/libMPC/node_modules/bs58check/LICENSE b/src/libMPC/node_modules/bs58check/LICENSE new file mode 100644 index 0000000..5dd5d5a --- /dev/null +++ b/src/libMPC/node_modules/bs58check/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Daniel Cousens + +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. diff --git a/src/libMPC/node_modules/bs58check/README.md b/src/libMPC/node_modules/bs58check/README.md new file mode 100644 index 0000000..58cf6f0 --- /dev/null +++ b/src/libMPC/node_modules/bs58check/README.md @@ -0,0 +1,27 @@ +# bs58check + +[![NPM Package](https://img.shields.io/npm/v/bs58check.svg?style=flat-square)](https://www.npmjs.org/package/bs58check) +[![Build Status](https://img.shields.io/travis/bitcoinjs/bs58check.svg?branch=master&style=flat-square)](https://travis-ci.org/bitcoinjs/bs58check) +[![Dependency status](https://img.shields.io/david/bitcoinjs/bs58check.svg?style=flat-square)](https://david-dm.org/bitcoinjs/bs58check#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A straight forward implementation of base58check extending upon bs58. + + +## Example + +```javascript +import bs58check from 'bs58check' + +var decoded = bs58check.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') + +console.log(decoded) +// => + +console.log(bs58check.encode(decoded)) +// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr +``` + + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/bs58check/package.json b/src/libMPC/node_modules/bs58check/package.json new file mode 100644 index 0000000..66d45a7 --- /dev/null +++ b/src/libMPC/node_modules/bs58check/package.json @@ -0,0 +1,69 @@ +{ + "name": "bs58check", + "version": "4.0.0", + "description": "A straightforward implementation of base58-check encoding", + "type": "module", + "keywords": [ + "base", + "base58", + "base58check", + "bitcoin", + "bs58", + "check", + "checksum", + "decode", + "decoding", + "encode", + "encoding", + "litecoin" + ], + "homepage": "https://github.com/bitcoinjs/bs58check", + "bugs": { + "url": "https://github.com/bitcoinjs/bs58check/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "files": [ + "src" + ], + "main": "src/cjs/index.cjs", + "module": "src/esm/index.js", + "types": "src/cjs/index.d.ts", + "exports": { + ".": { + "require": "./src/cjs/index.cjs", + "import": "./src/esm/index.js", + "types": "./src/cjs/index.d.ts" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/bs58check.git" + }, + "scripts": { + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json", + "clean": "rimraf src", + "gitdiff": "npm run build && git diff --exit-code", + "postbuild": "chmod +x ./fixup.sh && ./fixup.sh", + "coverage-report": "c8 report --reporter=lcov", + "coverage": "c8 --check-coverage --branches 90 --functions 90 npm run unit", + "standard": "ts-standard --ignore test --ignore src", + "test": "npm run standard -- --fix && npm run coverage", + "unit": "tape test/*.js" + }, + "dependencies": { + "@noble/hashes": "^1.2.0", + "bs58": "^6.0.0" + }, + "devDependencies": { + "@types/node": "^20.14.8", + "blake-hash": "^1.0.0", + "c8": "^10.1.2", + "rimraf": "^5.0.7", + "safe-buffer": "^5.1.2", + "standard": "^17.1.0", + "tape": "^5.3.0", + "ts-standard": "^12.0.2", + "typescript": "^5.5.2" + } +} diff --git a/src/libMPC/node_modules/bs58check/src/cjs/base.cjs b/src/libMPC/node_modules/bs58check/src/cjs/base.cjs new file mode 100644 index 0000000..addab50 --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/cjs/base.cjs @@ -0,0 +1,50 @@ +'use strict'; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = default_1; +var bs58_1 = __importDefault(require("bs58")); +function default_1(checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode(payload) { + var payloadU8 = Uint8Array.from(payload); + var checksum = checksumFn(payloadU8); + var length = payloadU8.length + 4; + var both = new Uint8Array(length); + both.set(payloadU8, 0); + both.set(checksum.subarray(0, 4), payloadU8.length); + return bs58_1.default.encode(both); + } + function decodeRaw(buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + // eslint-disable-next-line + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) + return; + return payload; + } + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe(str) { + var buffer = bs58_1.default.decodeUnsafe(str); + if (buffer == null) + return; + return decodeRaw(buffer); + } + function decode(str) { + var buffer = bs58_1.default.decode(str); + var payload = decodeRaw(buffer); + if (payload == null) + throw new Error('Invalid checksum'); + return payload; + } + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + }; +} diff --git a/src/libMPC/node_modules/bs58check/src/cjs/base.d.ts b/src/libMPC/node_modules/bs58check/src/cjs/base.d.ts new file mode 100644 index 0000000..4cfc64a --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/cjs/base.d.ts @@ -0,0 +1,5 @@ +export default function (checksumFn: (payload: Uint8Array | string) => Uint8Array): { + encode: (payload: Uint8Array | number[]) => string; + decode: (str: string) => Uint8Array; + decodeUnsafe: (str: string) => Uint8Array | undefined; +}; diff --git a/src/libMPC/node_modules/bs58check/src/cjs/index.cjs b/src/libMPC/node_modules/bs58check/src/cjs/index.cjs new file mode 100644 index 0000000..f456f27 --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/cjs/index.cjs @@ -0,0 +1,12 @@ +'use strict'; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var sha256_1 = require("@noble/hashes/sha256"); +var base_js_1 = __importDefault(require("./base.cjs")); +// SHA256(SHA256(buffer)) +function sha256x2(buffer) { + return (0, sha256_1.sha256)((0, sha256_1.sha256)(buffer)); +} +exports.default = (0, base_js_1.default)(sha256x2); diff --git a/src/libMPC/node_modules/bs58check/src/cjs/index.d.ts b/src/libMPC/node_modules/bs58check/src/cjs/index.d.ts new file mode 100644 index 0000000..b9e163a --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/cjs/index.d.ts @@ -0,0 +1,6 @@ +declare const _default: { + encode: (payload: Uint8Array | number[]) => string; + decode: (str: string) => Uint8Array; + decodeUnsafe: (str: string) => Uint8Array | undefined; +}; +export default _default; diff --git a/src/libMPC/node_modules/bs58check/src/esm/base.js b/src/libMPC/node_modules/bs58check/src/esm/base.js new file mode 100644 index 0000000..bf3d26e --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/esm/base.js @@ -0,0 +1,45 @@ +'use strict'; +import base58 from 'bs58'; +export default function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode(payload) { + var payloadU8 = Uint8Array.from(payload); + var checksum = checksumFn(payloadU8); + var length = payloadU8.length + 4; + var both = new Uint8Array(length); + both.set(payloadU8, 0); + both.set(checksum.subarray(0, 4), payloadU8.length); + return base58.encode(both); + } + function decodeRaw(buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + // eslint-disable-next-line + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) + return; + return payload; + } + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe(str) { + var buffer = base58.decodeUnsafe(str); + if (buffer == null) + return; + return decodeRaw(buffer); + } + function decode(str) { + var buffer = base58.decode(str); + var payload = decodeRaw(buffer); + if (payload == null) + throw new Error('Invalid checksum'); + return payload; + } + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + }; +} diff --git a/src/libMPC/node_modules/bs58check/src/esm/index.js b/src/libMPC/node_modules/bs58check/src/esm/index.js new file mode 100644 index 0000000..2458233 --- /dev/null +++ b/src/libMPC/node_modules/bs58check/src/esm/index.js @@ -0,0 +1,8 @@ +'use strict'; +import { sha256 } from '@noble/hashes/sha256'; +import bs58checkBase from './base.js'; +// SHA256(SHA256(buffer)) +function sha256x2(buffer) { + return sha256(sha256(buffer)); +} +export default bs58checkBase(sha256x2); diff --git a/src/libMPC/node_modules/cipher-base/.eslintrc b/src/libMPC/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/src/libMPC/node_modules/cipher-base/.npmignore b/src/libMPC/node_modules/cipher-base/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/src/libMPC/node_modules/cipher-base/.travis.yml b/src/libMPC/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/src/libMPC/node_modules/cipher-base/LICENSE b/src/libMPC/node_modules/cipher-base/LICENSE new file mode 100644 index 0000000..f06007a --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 crypto-browserify 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. diff --git a/src/libMPC/node_modules/cipher-base/README.md b/src/libMPC/node_modules/cipher-base/README.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/README.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/src/libMPC/node_modules/cipher-base/index.js b/src/libMPC/node_modules/cipher-base/index.js new file mode 100644 index 0000000..6728005 --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/index.js @@ -0,0 +1,99 @@ +var Buffer = require('safe-buffer').Buffer +var Transform = require('stream').Transform +var StringDecoder = require('string_decoder').StringDecoder +var inherits = require('inherits') + +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null +} +inherits(CipherBase, Transform) + +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out +} + +module.exports = CipherBase diff --git a/src/libMPC/node_modules/cipher-base/package.json b/src/libMPC/node_modules/cipher-base/package.json new file mode 100644 index 0000000..f372599 --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/package.json @@ -0,0 +1,32 @@ +{ + "name": "cipher-base", + "version": "1.0.4", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": "Calvin Metcalf ", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "standard": "^10.0.2", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + } +} diff --git a/src/libMPC/node_modules/cipher-base/test.js b/src/libMPC/node_modules/cipher-base/test.js new file mode 100644 index 0000000..29d3492 --- /dev/null +++ b/src/libMPC/node_modules/cipher-base/test.js @@ -0,0 +1,111 @@ +var Buffer = require('safe-buffer').Buffer +var CipherBase = require('./') + +var test = require('tape') +var inherits = require('inherits') + +test('basic version', function (t) { + function Cipher () { + CipherBase.call(this) + } + inherits(Cipher, CipherBase) + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (Buffer.from(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + inherits(Cipher, CipherBase) + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (Buffer.from(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + inherits(Cipher, CipherBase) + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (Buffer.from(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) + +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/src/libMPC/node_modules/create-hash/.travis.yml b/src/libMPC/node_modules/create-hash/.travis.yml new file mode 100644 index 0000000..da59431 --- /dev/null +++ b/src/libMPC/node_modules/create-hash/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "4" + - "5" + - "6" + - "7" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "7" + env: TEST_SUITE=standard +script: npm run $TEST_SUITE diff --git a/src/libMPC/node_modules/create-hash/LICENSE b/src/libMPC/node_modules/create-hash/LICENSE new file mode 100644 index 0000000..f06007a --- /dev/null +++ b/src/libMPC/node_modules/create-hash/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 crypto-browserify 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. diff --git a/src/libMPC/node_modules/create-hash/README.md b/src/libMPC/node_modules/create-hash/README.md new file mode 100644 index 0000000..bad028d --- /dev/null +++ b/src/libMPC/node_modules/create-hash/README.md @@ -0,0 +1,19 @@ +# create-hash + +[![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash) + +Node style hashes for use in the browser, with native hash functions in node. + +API is the same as hashes in node: +```js +var createHash = require('create-hash') +var hash = createHash('sha224') +hash.update('synchronous write') // optional encoding parameter +hash.digest() // synchronously get result with optional encoding parameter + +hash.write('write to it as a stream') +hash.end() // remember it's a stream +hash.read() // only if you ended it as a stream though +``` + +To get the JavaScript version even in node do `require('create-hash/browser')` diff --git a/src/libMPC/node_modules/create-hash/browser.js b/src/libMPC/node_modules/create-hash/browser.js new file mode 100644 index 0000000..01841bb --- /dev/null +++ b/src/libMPC/node_modules/create-hash/browser.js @@ -0,0 +1,30 @@ +'use strict' +var inherits = require('inherits') +var MD5 = require('md5.js') +var RIPEMD160 = require('ripemd160') +var sha = require('sha.js') +var Base = require('cipher-base') + +function Hash (hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) +} diff --git a/src/libMPC/node_modules/create-hash/index.js b/src/libMPC/node_modules/create-hash/index.js new file mode 100644 index 0000000..658f6a0 --- /dev/null +++ b/src/libMPC/node_modules/create-hash/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').createHash diff --git a/src/libMPC/node_modules/create-hash/md5.js b/src/libMPC/node_modules/create-hash/md5.js new file mode 100644 index 0000000..3643ee2 --- /dev/null +++ b/src/libMPC/node_modules/create-hash/md5.js @@ -0,0 +1,5 @@ +var MD5 = require('md5.js') + +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} diff --git a/src/libMPC/node_modules/create-hash/package.json b/src/libMPC/node_modules/create-hash/package.json new file mode 100644 index 0000000..16f385b --- /dev/null +++ b/src/libMPC/node_modules/create-hash/package.json @@ -0,0 +1,39 @@ +{ + "name": "create-hash", + "version": "1.2.0", + "description": "create hashes for browserify", + "browser": "browser.js", + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script standard && npm run-script unit", + "unit": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git@github.com:crypto-browserify/createHash.git" + }, + "keywords": [ + "crypto" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/createHash/issues" + }, + "homepage": "https://github.com/crypto-browserify/createHash", + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "safe-buffer": "^5.0.1", + "standard": "^10.0.2", + "tap-spec": "^2.1.2", + "tape": "^4.6.3" + }, + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } +} diff --git a/src/libMPC/node_modules/create-hash/test.js b/src/libMPC/node_modules/create-hash/test.js new file mode 100644 index 0000000..7c98f9f --- /dev/null +++ b/src/libMPC/node_modules/create-hash/test.js @@ -0,0 +1,41 @@ +var test = require('tape') + +var Buffer = require('safe-buffer').Buffer +var algorithms = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160', 'ripemd160'] +var encodings = ['hex', 'base64'] // ignore binary +var vectors = require('hash-test-vectors') +vectors.forEach(function (vector) { + vector.ripemd160 = vector.rmd160 +}) +var createHash = require('./browser') + +algorithms.forEach(function (algorithm) { + test('test ' + algorithm + ' against test vectors', function (t) { + vectors.forEach(function (obj, i) { + var input = Buffer.from(obj.input, 'base64') + var node = obj[algorithm] + var js = createHash(algorithm).update(input).digest('hex') + t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node) + }) + + encodings.forEach(function (encoding) { + vectors.forEach(function (obj, i) { + var input = Buffer.from(obj.input, 'base64').toString(encoding) + var node = obj[algorithm] + var js = createHash(algorithm).update(input, encoding).digest('hex') + t.equal(js, node, algorithm + '(testVector[' + i + '], ' + encoding + ') == ' + node) + }) + }) + + vectors.forEach(function (obj, i) { + var input = Buffer.from(obj.input, 'base64') + var node = obj[algorithm] + var hash = createHash(algorithm) + hash.end(input) + var js = hash.read().toString('hex') + t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node) + }) + + t.end() + }) +}) diff --git a/src/libMPC/node_modules/data-uri-to-buffer/README.md b/src/libMPC/node_modules/data-uri-to-buffer/README.md new file mode 100644 index 0000000..d0f2e05 --- /dev/null +++ b/src/libMPC/node_modules/data-uri-to-buffer/README.md @@ -0,0 +1,88 @@ +data-uri-to-buffer +================== +### Generate a Buffer instance from a [Data URI][rfc] string +[![Build Status](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer.svg?branch=master)](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer) + +This module accepts a ["data" URI][rfc] String of data, and returns a +node.js `Buffer` instance with the decoded data. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install data-uri-to-buffer +``` + + +Example +------- + +``` js +import dataUriToBuffer from 'data-uri-to-buffer'; + +// plain-text data is supported +let uri = 'data:,Hello%2C%20World!'; +let decoded = dataUriToBuffer(uri); +console.log(decoded.toString()); +// 'Hello, World!' + +// base64-encoded data is supported +uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D'; +decoded = dataUriToBuffer(uri); +console.log(decoded.toString()); +// 'Hello, World!' +``` + + +API +--- + +### dataUriToBuffer(String uri) → Buffer + +The `type` property on the Buffer instance gets set to the main type portion of +the "mediatype" portion of the "data" URI, or defaults to `"text/plain"` if not +specified. + +The `typeFull` property on the Buffer instance gets set to the entire +"mediatype" portion of the "data" URI (including all parameters), or defaults +to `"text/plain;charset=US-ASCII"` if not specified. + +The `charset` property on the Buffer instance gets set to the Charset portion of +the "mediatype" portion of the "data" URI, or defaults to `"US-ASCII"` if the +entire type is not specified, or defaults to `""` otherwise. + +*Note*: If the only the main type is specified but not the charset, e.g. +`"data:text/plain,abc"`, the charset is set to the empty string. The spec only +defaults to US-ASCII as charset if the entire type is not specified. + + +License +------- + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net> + +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. + +[rfc]: http://tools.ietf.org/html/rfc2397 diff --git a/src/libMPC/node_modules/data-uri-to-buffer/dist/index.d.ts b/src/libMPC/node_modules/data-uri-to-buffer/dist/index.d.ts new file mode 100644 index 0000000..2a3d91e --- /dev/null +++ b/src/libMPC/node_modules/data-uri-to-buffer/dist/index.d.ts @@ -0,0 +1,15 @@ +/// +export interface MimeBuffer extends Buffer { + type: string; + typeFull: string; + charset: string; +} +/** + * Returns a `Buffer` instance from the given data URI `uri`. + * + * @param {String} uri Data URI to turn into a Buffer instance + * @returns {Buffer} Buffer instance from Data URI + * @api public + */ +export declare function dataUriToBuffer(uri: string): MimeBuffer; +export default dataUriToBuffer; diff --git a/src/libMPC/node_modules/data-uri-to-buffer/dist/index.js b/src/libMPC/node_modules/data-uri-to-buffer/dist/index.js new file mode 100644 index 0000000..4ddd079 --- /dev/null +++ b/src/libMPC/node_modules/data-uri-to-buffer/dist/index.js @@ -0,0 +1,53 @@ +/** + * Returns a `Buffer` instance from the given data URI `uri`. + * + * @param {String} uri Data URI to turn into a Buffer instance + * @returns {Buffer} Buffer instance from Data URI + * @api public + */ +export function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + // strip newlines + uri = uri.replace(/\r?\n/g, ''); + // split the URI up into the "metadata" and the "data" portions + const firstComma = uri.indexOf(','); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError('malformed data: URI'); + } + // remove the "data:" scheme and parse the metadata + const meta = uri.substring(5, firstComma).split(';'); + let charset = ''; + let base64 = false; + const type = meta[0] || 'text/plain'; + let typeFull = type; + for (let i = 1; i < meta.length; i++) { + if (meta[i] === 'base64') { + base64 = true; + } + else if (meta[i]) { + typeFull += `;${meta[i]}`; + if (meta[i].indexOf('charset=') === 0) { + charset = meta[i].substring(8); + } + } + } + // defaults to US-ASCII only if type is not provided + if (!meta[0] && !charset.length) { + typeFull += ';charset=US-ASCII'; + charset = 'US-ASCII'; + } + // get the encoded data portion and decode URI-encoded chars + const encoding = base64 ? 'base64' : 'ascii'; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + // set `.type` and `.typeFull` properties to MIME type + buffer.type = type; + buffer.typeFull = typeFull; + // set the `.charset` property + buffer.charset = charset; + return buffer; +} +export default dataUriToBuffer; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/src/libMPC/node_modules/data-uri-to-buffer/dist/index.js.map b/src/libMPC/node_modules/data-uri-to-buffer/dist/index.js.map new file mode 100644 index 0000000..696504a --- /dev/null +++ b/src/libMPC/node_modules/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;gBACtC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;aAC/B;SACD;KACD;IACD,oDAAoD;IACpD,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QAChC,QAAQ,IAAI,mBAAmB,CAAC;QAChC,OAAO,GAAG,UAAU,CAAC;KACrB;IAED,4DAA4D;IAC5D,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7C,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAe,CAAC;IAEzD,sDAAsD;IACtD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAE3B,8BAA8B;IAC9B,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;IAEzB,OAAO,MAAM,CAAC;AACf,CAAC;AAED,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/src/libMPC/node_modules/data-uri-to-buffer/package.json b/src/libMPC/node_modules/data-uri-to-buffer/package.json new file mode 100644 index 0000000..9e42713 --- /dev/null +++ b/src/libMPC/node_modules/data-uri-to-buffer/package.json @@ -0,0 +1,62 @@ +{ + "name": "data-uri-to-buffer", + "version": "4.0.1", + "description": "Generate a Buffer instance from a Data URI string", + "type": "module", + "exports": "./dist/index.js", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist", + "src" + ], + "scripts": { + "build": "tsc", + "test": "jest", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-data-uri-to-buffer.git" + }, + "engines": { + "node": ">= 12" + }, + "keywords": [ + "data", + "uri", + "datauri", + "data-uri", + "buffer", + "convert", + "rfc2397", + "2397" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-data-uri-to-buffer/issues" + }, + "homepage": "https://github.com/TooTallNate/node-data-uri-to-buffer", + "devDependencies": { + "@types/jest": "^27.0.2", + "@types/node": "^12.20.36", + "jest": "^27.3.1", + "ts-jest": "^27.0.7", + "typescript": "^4.4.4" + }, + "jest": { + "preset": "ts-jest", + "globals": { + "ts-jest": { + "diagnostics": false, + "isolatedModules": true + } + }, + "verbose": false, + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.test.ts" + ] + } +} diff --git a/src/libMPC/node_modules/data-uri-to-buffer/src/index.ts b/src/libMPC/node_modules/data-uri-to-buffer/src/index.ts new file mode 100644 index 0000000..9e5749f --- /dev/null +++ b/src/libMPC/node_modules/data-uri-to-buffer/src/index.ts @@ -0,0 +1,68 @@ +export interface MimeBuffer extends Buffer { + type: string; + typeFull: string; + charset: string; +} + +/** + * Returns a `Buffer` instance from the given data URI `uri`. + * + * @param {String} uri Data URI to turn into a Buffer instance + * @returns {Buffer} Buffer instance from Data URI + * @api public + */ +export function dataUriToBuffer(uri: string): MimeBuffer { + if (!/^data:/i.test(uri)) { + throw new TypeError( + '`uri` does not appear to be a Data URI (must begin with "data:")' + ); + } + + // strip newlines + uri = uri.replace(/\r?\n/g, ''); + + // split the URI up into the "metadata" and the "data" portions + const firstComma = uri.indexOf(','); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError('malformed data: URI'); + } + + // remove the "data:" scheme and parse the metadata + const meta = uri.substring(5, firstComma).split(';'); + + let charset = ''; + let base64 = false; + const type = meta[0] || 'text/plain'; + let typeFull = type; + for (let i = 1; i < meta.length; i++) { + if (meta[i] === 'base64') { + base64 = true; + } else if(meta[i]) { + typeFull += `;${ meta[i]}`; + if (meta[i].indexOf('charset=') === 0) { + charset = meta[i].substring(8); + } + } + } + // defaults to US-ASCII only if type is not provided + if (!meta[0] && !charset.length) { + typeFull += ';charset=US-ASCII'; + charset = 'US-ASCII'; + } + + // get the encoded data portion and decode URI-encoded chars + const encoding = base64 ? 'base64' : 'ascii'; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding) as MimeBuffer; + + // set `.type` and `.typeFull` properties to MIME type + buffer.type = type; + buffer.typeFull = typeFull; + + // set the `.charset` property + buffer.charset = charset; + + return buffer; +} + +export default dataUriToBuffer; diff --git a/src/libMPC/node_modules/ecpair/LICENSE b/src/libMPC/node_modules/ecpair/LICENSE new file mode 100644 index 0000000..b662082 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011-2021 bitcoinjs-lib 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. diff --git a/src/libMPC/node_modules/ecpair/README.md b/src/libMPC/node_modules/ecpair/README.md new file mode 100644 index 0000000..4cd17a4 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/README.md @@ -0,0 +1,48 @@ +# ecpair +[![Github CI](https://github.com/bitcoinjs/ecpair/actions/workflows/main_ci.yml/badge.svg)](https://github.com/bitcoinjs/ecpair/actions/workflows/main_ci.yml) [![NPM](https://img.shields.io/npm/v/ecpair.svg)](https://www.npmjs.org/package/ecpair) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) + +A library for managing SECP256k1 keypairs written in TypeScript with transpiled JavaScript committed to git. + +## Example + +TypeScript + +``` typescript +import { Signer, SignerAsync, ECPairInterface, ECPairFactory, ECPairAPI, TinySecp256k1Interface } from 'ecpair'; +import * as crypto from 'crypto'; + +// You need to provide the ECC library. The ECC library must implement +// all the methods of the `TinySecp256k1Interface` interface. +const tinysecp: TinySecp256k1Interface = require('tiny-secp256k1'); +const ECPair: ECPairAPI = ECPairFactory(tinysecp); + +// You don't need to explicitly write ECPairInterface, but just to show +// that the keyPair implements the interface this example includes it. + +// From WIF +const keyPair1: ECPairInterface = ECPair.fromWIF('KynD8ZKdViVo5W82oyxvE18BbG6nZPVQ8Td8hYbwU94RmyUALUik'); +// Random private key +const keyPair2 = ECPair.fromPrivateKey(crypto.randomBytes(32)); +// OR (uses randombytes library, compatible with browser) +const keyPair3 = ECPair.makeRandom(); +// OR use your own custom random buffer generator BE CAREFUL!!!! +const customRandomBufferFunc = (size: number): Buffer => crypto.randomBytes(size); +const keyPair4 = ECPair.makeRandom({ rng: customRandomBufferFunc }); +// From pubkey (33 or 65 byte DER format public key) +const keyPair5 = ECPair.fromPublicKey(keyPair1.publicKey); + +// Pass a custom network +const network = {}; // Your custom network object here +ECPair.makeRandom({ network }); +ECPair.fromPrivateKey(crypto.randomBytes(32), { network }); +ECPair.fromPublicKey(keyPair1.publicKey, { network }); +// fromWIF will check the WIF version against the network you pass in +// pass in multiple networks if you are not sure +ECPair.fromWIF('wif key...', network); +const network2 = {}; // Your custom network object here +const network3 = {}; // Your custom network object here +ECPair.fromWIF('wif key...', [network, network2, network3]); +``` + +## LICENSE [MIT](LICENSE) +Written and tested by [bitcoinjs-lib](https://github.com/bitcoinjs/bitcoinjs-lib) contributors since 2014. diff --git a/src/libMPC/node_modules/ecpair/package.json b/src/libMPC/node_modules/ecpair/package.json new file mode 100644 index 0000000..1490514 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/package.json @@ -0,0 +1,80 @@ +{ + "name": "ecpair", + "version": "2.0.0", + "description": "Client-side Bitcoin JavaScript library ECPair", + "main": "./src/ecpair.js", + "types": "./src/ecpair.d.ts", + "engines": { + "node": ">=8.0.0" + }, + "keywords": [ + "bitcoinjs", + "bitcoin", + "browserify", + "javascript", + "bitcoinjs" + ], + "scripts": { + "audit": "NPM_AUDIT_IGNORE_DEV=1 NPM_AUDIT_IGNORE_LEVEL=low npm-audit-whitelister .npm-audit-whitelister.json", + "build": "npm run clean && tsc -p ./tsconfig.json && npm run formatjs", + "build:tests": "npm run clean:jstests && tsc -p ./test/tsconfig.json", + "clean": "rimraf src", + "clean:jstests": "rimraf 'test/**/!(ts-node-register)*.js'", + "coverage-report": "npm run build && npm run nobuild:coverage-report", + "coverage-html": "npm run build && npm run nobuild:coverage-html", + "coverage": "npm run build && npm run nobuild:coverage", + "format": "npm run prettier -- --write", + "formatjs": "npm run prettierjs -- --write", + "format:ci": "npm run prettier -- --check && npm run prettierjs -- --check", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "tslint -p tsconfig.json -c tslint.json", + "lint:tests": "tslint -p test/tsconfig.json -c tslint.json", + "mocha:ts": "mocha --recursive --require test/ts-node-register", + "nobuild:coverage-report": "nyc report --reporter=lcov", + "nobuild:coverage-html": "nyc report --reporter=html", + "nobuild:coverage": "npm run build:tests && nyc --check-coverage --branches 90 --functions 90 --lines 90 mocha && npm run clean:jstests", + "nobuild:unit": "npm run mocha:ts -- 'test/*.ts'", + "prettier": "prettier \"ts_src/**/*.ts\" \"test/**/*.ts\" --ignore-path ./.prettierignore", + "prettierjs": "prettier \"src/**/*.js\" --ignore-path ./.prettierignore", + "test": "npm run build && npm run format:ci && npm run lint && npm run nobuild:coverage", + "unit": "npm run build && npm run nobuild:unit" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/ecpair.git" + }, + "files": [ + "src" + ], + "dependencies": { + "randombytes": "^2.1.0", + "typeforce": "^1.18.0", + "wif": "^2.0.6" + }, + "devDependencies": { + "@types/mocha": "^5.2.7", + "@types/node": "^16.11.1", + "@types/proxyquire": "^1.3.28", + "@types/randombytes": "^2.0.0", + "@types/wif": "^2.0.2", + "bip39": "^3.0.2", + "bip65": "^1.0.1", + "bip68": "^1.0.3", + "bn.js": "^4.11.8", + "bs58": "^4.0.0", + "dhttp": "^3.0.0", + "hoodwink": "^2.0.0", + "minimaldata": "^1.0.2", + "mocha": "^7.1.1", + "npm-audit-whitelister": "^1.0.2", + "nyc": "^15.1.0", + "prettier": "^2.4.1", + "proxyquire": "^2.0.1", + "rimraf": "^2.6.3", + "tiny-secp256k1": "^2.1.2", + "ts-node": "^8.3.0", + "tslint": "^6.1.3", + "typescript": "^4.4.4" + }, + "license": "MIT" +} diff --git a/src/libMPC/node_modules/ecpair/src/ecpair.d.ts b/src/libMPC/node_modules/ecpair/src/ecpair.d.ts new file mode 100644 index 0000000..dcfd824 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/ecpair.d.ts @@ -0,0 +1,49 @@ +/// +import { Network } from './networks'; +import * as networks from './networks'; +export { networks }; +interface ECPairOptions { + compressed?: boolean; + network?: Network; + rng?(arg0: number): Buffer; +} +export interface Signer { + publicKey: Buffer; + network?: any; + sign(hash: Buffer, lowR?: boolean): Buffer; + getPublicKey?(): Buffer; +} +export interface SignerAsync { + publicKey: Buffer; + network?: any; + sign(hash: Buffer, lowR?: boolean): Promise; + getPublicKey?(): Buffer; +} +export interface ECPairInterface extends Signer { + compressed: boolean; + network: Network; + lowR: boolean; + privateKey?: Buffer; + toWIF(): string; + verify(hash: Buffer, signature: Buffer): boolean; + verifySchnorr(hash: Buffer, signature: Buffer): boolean; + signSchnorr(hash: Buffer): Buffer; +} +export interface ECPairAPI { + isPoint(maybePoint: any): boolean; + fromPrivateKey(buffer: Buffer, options?: ECPairOptions): ECPairInterface; + fromPublicKey(buffer: Buffer, options?: ECPairOptions): ECPairInterface; + fromWIF(wifString: string, network?: Network | Network[]): ECPairInterface; + makeRandom(options?: ECPairOptions): ECPairInterface; +} +export interface TinySecp256k1Interface { + isPoint(p: Uint8Array): boolean; + pointCompress(p: Uint8Array, compressed?: boolean): Uint8Array; + isPrivate(d: Uint8Array): boolean; + pointFromScalar(d?: Uint8Array, compressed?: boolean): Uint8Array; + sign(h: Uint8Array, d: Uint8Array, e?: Uint8Array): Uint8Array; + signSchnorr?(h: Uint8Array, d: Uint8Array, e?: Uint8Array): Uint8Array; + verify(h: Uint8Array, Q: Uint8Array, signature: Uint8Array, strict?: boolean): boolean; + verifySchnorr?(h: Uint8Array, Q: Uint8Array, signature: Uint8Array): boolean; +} +export declare function ECPairFactory(ecc: TinySecp256k1Interface): ECPairAPI; diff --git a/src/libMPC/node_modules/ecpair/src/ecpair.js b/src/libMPC/node_modules/ecpair/src/ecpair.js new file mode 100644 index 0000000..88c5e59 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/ecpair.js @@ -0,0 +1,136 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.ECPairFactory = exports.networks = void 0; +const networks = require('./networks'); +exports.networks = networks; +const types = require('./types'); +const randomBytes = require('randombytes'); +const wif = require('wif'); +const testecc_1 = require('./testecc'); +const isOptions = types.typeforce.maybe( + types.typeforce.compile({ + compressed: types.maybe(types.Boolean), + network: types.maybe(types.Network), + }), +); +function ECPairFactory(ecc) { + (0, testecc_1.testEcc)(ecc); + function isPoint(maybePoint) { + return ecc.isPoint(maybePoint); + } + function fromPrivateKey(buffer, options) { + types.typeforce(types.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + types.typeforce(isOptions, options); + return new ECPair(buffer, undefined, options); + } + function fromPublicKey(buffer, options) { + types.typeforce(ecc.isPoint, buffer); + types.typeforce(isOptions, options); + return new ECPair(undefined, buffer, options); + } + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types.Array(network)) { + network = network + .filter((x) => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || networks.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + function makeRandom(options) { + types.typeforce(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + types.typeforce(types.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + class ECPair { + __D; + __Q; + compressed; + network; + lowR; + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || networks.bitcoin; + if (__Q !== undefined) + this.__Q = Buffer.from(ecc.pointCompress(__Q, this.compressed)); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) + this.__Q = Buffer.from(ecc.pointFromScalar(this.__D, this.compressed)); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return Buffer.from(ecc.sign(hash, this.__D)); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.sign(hash, this.__D, extraData); + } + return Buffer.from(sig); + } + } + signSchnorr(hash) { + if (!this.privateKey) throw new Error('Missing private key'); + if (!ecc.signSchnorr) + throw new Error('signSchnorr not supported by ecc library'); + return Buffer.from(ecc.signSchnorr(hash, this.privateKey)); + } + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + verifySchnorr(hash, signature) { + if (!ecc.verifySchnorr) + throw new Error('verifySchnorr not supported by ecc library'); + return ecc.verifySchnorr(hash, this.publicKey.subarray(1, 33), signature); + } + } + return { + isPoint, + fromPrivateKey, + fromPublicKey, + fromWIF, + makeRandom, + }; +} +exports.ECPairFactory = ECPairFactory; diff --git a/src/libMPC/node_modules/ecpair/src/index.d.ts b/src/libMPC/node_modules/ecpair/src/index.d.ts new file mode 100644 index 0000000..5c001b6 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/index.d.ts @@ -0,0 +1 @@ +export { ECPairFactory as default, ECPairFactory, Signer, SignerAsync, ECPairAPI, ECPairInterface, TinySecp256k1Interface, } from './ecpair'; diff --git a/src/libMPC/node_modules/ecpair/src/index.js b/src/libMPC/node_modules/ecpair/src/index.js new file mode 100644 index 0000000..e365a35 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/index.js @@ -0,0 +1,16 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.ECPairFactory = exports.default = void 0; +var ecpair_1 = require('./ecpair'); +Object.defineProperty(exports, 'default', { + enumerable: true, + get: function () { + return ecpair_1.ECPairFactory; + }, +}); +Object.defineProperty(exports, 'ECPairFactory', { + enumerable: true, + get: function () { + return ecpair_1.ECPairFactory; + }, +}); diff --git a/src/libMPC/node_modules/ecpair/src/networks.d.ts b/src/libMPC/node_modules/ecpair/src/networks.d.ts new file mode 100644 index 0000000..33a4baa --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/networks.d.ts @@ -0,0 +1,15 @@ +export interface Network { + messagePrefix: string; + bech32: string; + bip32: Bip32; + pubKeyHash: number; + scriptHash: number; + wif: number; +} +interface Bip32 { + public: number; + private: number; +} +export declare const bitcoin: Network; +export declare const testnet: Network; +export {}; diff --git a/src/libMPC/node_modules/ecpair/src/networks.js b/src/libMPC/node_modules/ecpair/src/networks.js new file mode 100644 index 0000000..1a92a8f --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/networks.js @@ -0,0 +1,25 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.testnet = exports.bitcoin = void 0; +exports.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, +}; +exports.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; diff --git a/src/libMPC/node_modules/ecpair/src/testecc.d.ts b/src/libMPC/node_modules/ecpair/src/testecc.d.ts new file mode 100644 index 0000000..bff8d27 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/testecc.d.ts @@ -0,0 +1,2 @@ +import { TinySecp256k1Interface } from './ecpair'; +export declare function testEcc(ecc: TinySecp256k1Interface): void; diff --git a/src/libMPC/node_modules/ecpair/src/testecc.js b/src/libMPC/node_modules/ecpair/src/testecc.js new file mode 100644 index 0000000..94121bd --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/testecc.js @@ -0,0 +1,153 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.testEcc = void 0; +const h = (hex) => Buffer.from(hex, 'hex'); +function testEcc(ecc) { + assert( + ecc.isPoint( + h('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + !ecc.isPoint( + h('030000000000000000000000000000000000000000000000000000000000000005'), + ), + ); + assert( + ecc.isPrivate( + h('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + // order - 1 + assert( + ecc.isPrivate( + h('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140'), + ), + ); + // 0 + assert( + !ecc.isPrivate( + h('0000000000000000000000000000000000000000000000000000000000000000'), + ), + ); + // order + assert( + !ecc.isPrivate( + h('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + ), + ); + // order + 1 + assert( + !ecc.isPrivate( + h('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364142'), + ), + ); + assert( + Buffer.from( + ecc.pointCompress( + h( + '0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + ), + true, + ), + ).equals( + h('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + Buffer.from( + ecc.pointCompress( + h( + '0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + ), + false, + ), + ).equals( + h( + '0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + ), + ), + ); + assert( + Buffer.from( + ecc.pointCompress( + h('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + true, + ), + ).equals( + h('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + Buffer.from( + ecc.pointCompress( + h('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + false, + ), + ).equals( + h( + '0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + ), + ), + ); + assert( + Buffer.from( + ecc.pointFromScalar( + h('b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af'), + ), + ).equals( + h('02b07ba9dca9523b7ef4bd97703d43d20399eb698e194704791a25ce77a400df99'), + ), + ); + assert( + Buffer.from( + ecc.sign( + h('5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed'), + h('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140'), + ), + ).equals( + h( + '54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5', + ), + ), + ); + assert( + ecc.verify( + h('5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed'), + h('0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + h( + '54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5', + ), + ), + ); + if (ecc.signSchnorr) { + assert( + Buffer.from( + ecc.signSchnorr( + h('7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c'), + h('c90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b14e5c9'), + h('c87aa53824b4d7ae2eb035a2b5bbbccc080e76cdc6d1692c4b0b62d798e6d906'), + ), + ).equals( + h( + '5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7', + ), + ), + ); + } + if (ecc.verifySchnorr) { + assert( + ecc.verifySchnorr( + h('7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c'), + h('dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8'), + h( + '5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7', + ), + ), + ); + } +} +exports.testEcc = testEcc; +function assert(bool) { + if (!bool) throw new Error('ecc library invalid'); +} diff --git a/src/libMPC/node_modules/ecpair/src/types.d.ts b/src/libMPC/node_modules/ecpair/src/types.d.ts new file mode 100644 index 0000000..198544a --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/types.d.ts @@ -0,0 +1,6 @@ +export declare const typeforce: any; +export declare const Network: any; +export declare const Buffer256bit: any; +export declare const Array: any; +export declare const Boolean: any; +export declare const maybe: any; diff --git a/src/libMPC/node_modules/ecpair/src/types.js b/src/libMPC/node_modules/ecpair/src/types.js new file mode 100644 index 0000000..664ffd4 --- /dev/null +++ b/src/libMPC/node_modules/ecpair/src/types.js @@ -0,0 +1,28 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.maybe = + exports.Boolean = + exports.Array = + exports.Buffer256bit = + exports.Network = + exports.typeforce = + void 0; +exports.typeforce = require('typeforce'); +// exposed, external API +exports.Network = exports.typeforce.compile({ + messagePrefix: exports.typeforce.oneOf( + exports.typeforce.Buffer, + exports.typeforce.String, + ), + bip32: { + public: exports.typeforce.UInt32, + private: exports.typeforce.UInt32, + }, + pubKeyHash: exports.typeforce.UInt8, + scriptHash: exports.typeforce.UInt8, + wif: exports.typeforce.UInt8, +}); +exports.Buffer256bit = exports.typeforce.BufferN(32); +exports.Array = exports.typeforce.Array; +exports.Boolean = exports.typeforce.Boolean; // tslint:disable-line variable-name +exports.maybe = exports.typeforce.maybe; diff --git a/src/libMPC/node_modules/fetch-blob/LICENSE b/src/libMPC/node_modules/fetch-blob/LICENSE new file mode 100644 index 0000000..0d31723 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 David Frank + +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. diff --git a/src/libMPC/node_modules/fetch-blob/README.md b/src/libMPC/node_modules/fetch-blob/README.md new file mode 100644 index 0000000..fb3e198 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/README.md @@ -0,0 +1,106 @@ +# fetch-blob + +[![npm version][npm-image]][npm-url] +[![build status][ci-image]][ci-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] + +A Blob implementation in Node.js, originally from [node-fetch](https://github.com/node-fetch/node-fetch). + +## Installation + +```sh +npm install fetch-blob +``` + +
+ Upgrading from 2x to 3x + + Updating from 2 to 3 should be a breeze since there is not many changes to the blob specification. + The major cause of a major release is coding standards. + - internal WeakMaps was replaced with private fields + - internal Buffer.from was replaced with TextEncoder/Decoder + - internal buffers was replaced with Uint8Arrays + - CommonJS was replaced with ESM + - The node stream returned by calling `blob.stream()` was replaced with whatwg streams + - (Read "Differences from other blobs" for more info.) + +
+ +
+ Differences from other Blobs + + - Unlike NodeJS `buffer.Blob` (Added in: v15.7.0) and browser native Blob this polyfilled version can't be sent via PostMessage + - This blob version is more arbitrary, it can be constructed with blob parts that isn't a instance of itself + it has to look and behave as a blob to be accepted as a blob part. + - The benefit of this is that you can create other types of blobs that don't contain any internal data that has to be read in other ways, such as the `BlobDataItem` created in `from.js` that wraps a file path into a blob-like item and read lazily (nodejs plans to [implement this][fs-blobs] as well) + - The `blob.stream()` is the most noticeable differences. It returns a WHATWG stream now. to keep it as a node stream you would have to do: + + ```js + import {Readable} from 'stream' + const stream = Readable.from(blob.stream()) + ``` +
+ +## Usage + +```js +// Ways to import +// (PS it's dependency free ESM package so regular http-import from CDN works too) +import Blob from 'fetch-blob' +import File from 'fetch-blob/file.js' + +import {Blob} from 'fetch-blob' +import {File} from 'fetch-blob/file.js' + +const {Blob} = await import('fetch-blob') + + +// Ways to read the blob: +const blob = new Blob(['hello, world']) + +await blob.text() +await blob.arrayBuffer() +for await (let chunk of blob.stream()) { ... } +blob.stream().getReader().read() +blob.stream().getReader({mode: 'byob'}).read(view) +``` + +### Blob part backed up by filesystem + +`fetch-blob/from.js` comes packed with tools to convert any filepath into either a Blob or a File +It will not read the content into memory. It will only stat the file for last modified date and file size. + +```js +// The default export is sync and use fs.stat to retrieve size & last modified as a blob +import blobFromSync from 'fetch-blob/from.js' +import {File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync} from 'fetch-blob/from.js' + +const fsFile = fileFromSync('./2-GiB-file.bin', 'application/octet-stream') +const fsBlob = await blobFrom('./2-GiB-file.mp4') + +// Not a 4 GiB memory snapshot, just holds references +// points to where data is located on the disk +const blob = new Blob([fsFile, fsBlob, 'memory', new Uint8Array(10)]) +console.log(blob.size) // ~4 GiB +``` + +`blobFrom|blobFromSync|fileFrom|fileFromSync(path, [mimetype])` + +### Creating Blobs backed up by other async sources +Our Blob & File class are more generic then any other polyfills in the way that it can accept any blob look-a-like item +An example of this is that our blob implementation can be constructed with parts coming from [BlobDataItem](https://github.com/node-fetch/fetch-blob/blob/8ef89adad40d255a3bbd55cf38b88597c1cd5480/from.js#L32) (aka a filepath) or from [buffer.Blob](https://nodejs.org/api/buffer.html#buffer_new_buffer_blob_sources_options), It dose not have to implement all the methods - just enough that it can be read/understood by our Blob implementation. The minium requirements is that it has `Symbol.toStringTag`, `size`, `slice()` and either a `stream()` or a `arrayBuffer()` method. If you then wrap it in our Blob or File `new Blob([blobDataItem])` then you get all of the other methods that should be implemented in a blob or file + +An example of this could be to create a file or blob like item coming from a remote HTTP request. Or from a DataBase + +See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and [tests](https://github.com/node-fetch/fetch-blob/blob/master/test.js) for more details of how to use the Blob. + +[npm-image]: https://flat.badgen.net/npm/v/fetch-blob +[npm-url]: https://www.npmjs.com/package/fetch-blob +[ci-image]: https://github.com/node-fetch/fetch-blob/workflows/CI/badge.svg +[ci-url]: https://github.com/node-fetch/fetch-blob/actions +[codecov-image]: https://flat.badgen.net/codecov/c/github/node-fetch/fetch-blob/master +[codecov-url]: https://codecov.io/gh/node-fetch/fetch-blob +[install-size-image]: https://flat.badgen.net/packagephobia/install/fetch-blob +[install-size-url]: https://packagephobia.now.sh/result?p=fetch-blob +[fs-blobs]: https://github.com/nodejs/node/issues/37340 diff --git a/src/libMPC/node_modules/fetch-blob/file.d.ts b/src/libMPC/node_modules/fetch-blob/file.d.ts new file mode 100644 index 0000000..d4b89bc --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/file.d.ts @@ -0,0 +1,2 @@ +/** @type {typeof globalThis.File} */ export const File: typeof globalThis.File; +export default File; diff --git a/src/libMPC/node_modules/fetch-blob/file.js b/src/libMPC/node_modules/fetch-blob/file.js new file mode 100644 index 0000000..7b26538 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/file.js @@ -0,0 +1,49 @@ +import Blob from './index.js' + +const _File = class File extends Blob { + #lastModified = 0 + #name = '' + + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */// @ts-ignore + constructor (fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`) + } + super(fileBits, options) + + if (options === null) options = {} + + // Simulate WebIDL type casting for NaN value in lastModified option. + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified) + if (!Number.isNaN(lastModified)) { + this.#lastModified = lastModified + } + + this.#name = String(fileName) + } + + get name () { + return this.#name + } + + get lastModified () { + return this.#lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } + + static [Symbol.hasInstance] (object) { + return !!object && object instanceof Blob && + /^(File)$/.test(object[Symbol.toStringTag]) + } +} + +/** @type {typeof globalThis.File} */// @ts-ignore +export const File = _File +export default File diff --git a/src/libMPC/node_modules/fetch-blob/from.d.ts b/src/libMPC/node_modules/fetch-blob/from.d.ts new file mode 100644 index 0000000..530b99b --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/from.d.ts @@ -0,0 +1,26 @@ +export default blobFromSync; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +export function blobFromSync(path: string, type?: string): Blob; +import File from "./file.js"; +import Blob from "./index.js"; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +export function blobFrom(path: string, type?: string): Promise; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +export function fileFrom(path: string, type?: string): Promise; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +export function fileFromSync(path: string, type?: string): File; +export { File, Blob }; diff --git a/src/libMPC/node_modules/fetch-blob/from.js b/src/libMPC/node_modules/fetch-blob/from.js new file mode 100644 index 0000000..9eaf8bf --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/from.js @@ -0,0 +1,100 @@ +import { statSync, createReadStream, promises as fs } from 'node:fs' +import { basename } from 'node:path' +import DOMException from 'node-domexception' + +import File from './file.js' +import Blob from './index.js' + +const { stat } = fs + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const blobFromSync = (path, type) => fromBlob(statSync(path), path, type) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const fileFromSync = (path, type) => fromFile(statSync(path), path, type) + +// @ts-ignore +const fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], { type }) + +// @ts-ignore +const fromFile = (stat, path, type = '') => new File([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], basename(path), { type, lastModified: stat.mtimeMs }) + +/** + * This is a blob backed up by a file on the disk + * with minium requirement. Its wrapped around a Blob as a blobPart + * so you have no direct access to this. + * + * @private + */ +class BlobDataItem { + #path + #start + + constructor (options) { + this.#path = options.path + this.#start = options.start + this.size = options.size + this.lastModified = options.lastModified + } + + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice (start, end) { + return new BlobDataItem({ + path: this.#path, + lastModified: this.lastModified, + size: end - start, + start: this.#start + start + }) + } + + async * stream () { + const { mtimeMs } = await stat(this.#path) + if (mtimeMs > this.lastModified) { + throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError') + } + yield * createReadStream(this.#path, { + start: this.#start, + end: this.#start + this.size - 1 + }) + } + + get [Symbol.toStringTag] () { + return 'Blob' + } +} + +export default blobFromSync +export { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync } diff --git a/src/libMPC/node_modules/fetch-blob/index.d.ts b/src/libMPC/node_modules/fetch-blob/index.d.ts new file mode 100644 index 0000000..7a68957 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/index.d.ts @@ -0,0 +1,3 @@ +/** @type {typeof globalThis.Blob} */ +export const Blob: typeof globalThis.Blob; +export default Blob; diff --git a/src/libMPC/node_modules/fetch-blob/index.js b/src/libMPC/node_modules/fetch-blob/index.js new file mode 100644 index 0000000..2542ac2 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/index.js @@ -0,0 +1,250 @@ +/*! fetch-blob. MIT License. Jimmy Wärting */ + +// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x) +// Node has recently added whatwg stream into core + +import './streams.cjs' + +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +/** @param {(Blob | Uint8Array)[]} parts */ +async function * toIterator (parts, clone = true) { + for (const part of parts) { + if ('stream' in part) { + yield * (/** @type {AsyncIterableIterator} */ (part.stream())) + } else if (ArrayBuffer.isView(part)) { + if (clone) { + let position = part.byteOffset + const end = part.byteOffset + part.byteLength + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE) + const chunk = part.buffer.slice(position, position + size) + position += chunk.byteLength + yield new Uint8Array(chunk) + } + } else { + yield part + } + /* c8 ignore next 10 */ + } else { + // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob) + let position = 0, b = (/** @type {Blob} */ (part)) + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + yield new Uint8Array(buffer) + } + } + } +} + +const _Blob = class Blob { + /** @type {Array.<(Blob|Uint8Array)>} */ + #parts = [] + #type = '' + #size = 0 + #endings = 'transparent' + + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor (blobParts = [], options = {}) { + if (typeof blobParts !== 'object' || blobParts === null) { + throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.') + } + + if (typeof blobParts[Symbol.iterator] !== 'function') { + throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.') + } + + if (typeof options !== 'object' && typeof options !== 'function') { + throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.') + } + + if (options === null) options = {} + + const encoder = new TextEncoder() + for (const element of blobParts) { + let part + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)) + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)) + } else if (element instanceof Blob) { + part = element + } else { + part = encoder.encode(`${element}`) + } + + this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size + this.#parts.push(part) + } + + this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}` + const type = options.type === undefined ? '' : String(options.type) + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '' + } + + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size () { + return this.#size + } + + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type () { + return this.#type + } + + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text () { + // More optimized than using this.arrayBuffer() + // that requires twice as much ram + const decoder = new TextDecoder() + let str = '' + for await (const part of toIterator(this.#parts, false)) { + str += decoder.decode(part, { stream: true }) + } + // Remaining + str += decoder.decode() + return str + } + + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer () { + // Easier way... Just a unnecessary overhead + // const view = new Uint8Array(this.size); + // await this.stream().getReader({mode: 'byob'}).read(view); + // return view.buffer; + + const data = new Uint8Array(this.size) + let offset = 0 + for await (const chunk of toIterator(this.#parts, false)) { + data.set(chunk, offset) + offset += chunk.length + } + + return data.buffer + } + + stream () { + const it = toIterator(this.#parts, true) + + return new globalThis.ReadableStream({ + // @ts-ignore + type: 'bytes', + async pull (ctrl) { + const chunk = await it.next() + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value) + }, + + async cancel () { + await it.return() + } + }) + } + + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice (start = 0, end = this.size, type = '') { + const { size } = this + + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size) + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size) + + const span = Math.max(relativeEnd - relativeStart, 0) + const parts = this.#parts + const blobParts = [] + let added = 0 + + for (const part of parts) { + // don't add the overflow to new blobParts + if (added >= span) { + break + } + + const size = ArrayBuffer.isView(part) ? part.byteLength : part.size + if (relativeStart && size <= relativeStart) { + // Skip the beginning and change the relative + // start & end position as we skip the unwanted parts + relativeStart -= size + relativeEnd -= size + } else { + let chunk + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size, relativeEnd)) + added += chunk.byteLength + } else { + chunk = part.slice(relativeStart, Math.min(size, relativeEnd)) + added += chunk.size + } + relativeEnd -= size + blobParts.push(chunk) + relativeStart = 0 // All next sequential parts should start at 0 + } + } + + const blob = new Blob([], { type: String(type).toLowerCase() }) + blob.#size = span + blob.#parts = blobParts + + return blob + } + + get [Symbol.toStringTag] () { + return 'Blob' + } + + static [Symbol.hasInstance] (object) { + return ( + object && + typeof object === 'object' && + typeof object.constructor === 'function' && + ( + typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function' + ) && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) + } +} + +Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}) + +/** @type {typeof globalThis.Blob} */ +export const Blob = _Blob +export default Blob diff --git a/src/libMPC/node_modules/fetch-blob/package.json b/src/libMPC/node_modules/fetch-blob/package.json new file mode 100644 index 0000000..9d07f39 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/package.json @@ -0,0 +1,56 @@ +{ + "name": "fetch-blob", + "version": "3.2.0", + "description": "Blob & File implementation in Node.js, originally from node-fetch.", + "main": "index.js", + "type": "module", + "files": [ + "from.js", + "file.js", + "file.d.ts", + "index.js", + "index.d.ts", + "from.d.ts", + "streams.cjs" + ], + "scripts": { + "test": "node --experimental-loader ./test/http-loader.js ./test/test-wpt-in-node.js", + "report": "c8 --reporter json --reporter text npm run test", + "coverage": "npm run report && codecov -f coverage/coverage-final.json", + "prepublishOnly": "tsc --declaration --emitDeclarationOnly --allowJs index.js from.js" + }, + "repository": "https://github.com/node-fetch/fetch-blob.git", + "keywords": [ + "blob", + "file", + "node-fetch" + ], + "engines": { + "node": "^12.20 || >= 14.13" + }, + "author": "Jimmy Wärting (https://jimmy.warting.se)", + "license": "MIT", + "bugs": { + "url": "https://github.com/node-fetch/fetch-blob/issues" + }, + "homepage": "https://github.com/node-fetch/fetch-blob#readme", + "devDependencies": { + "@types/node": "^17.0.9", + "c8": "^7.11.0", + "typescript": "^4.5.4" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + } +} diff --git a/src/libMPC/node_modules/fetch-blob/streams.cjs b/src/libMPC/node_modules/fetch-blob/streams.cjs new file mode 100644 index 0000000..f760959 --- /dev/null +++ b/src/libMPC/node_modules/fetch-blob/streams.cjs @@ -0,0 +1,51 @@ +/* c8 ignore start */ +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +if (!globalThis.ReadableStream) { + // `node:stream/web` got introduced in v16.5.0 as experimental + // and it's preferred over the polyfilled version. So we also + // suppress the warning that gets emitted by NodeJS for using it. + try { + const process = require('node:process') + const { emitWarning } = process + try { + process.emitWarning = () => {} + Object.assign(globalThis, require('node:stream/web')) + process.emitWarning = emitWarning + } catch (error) { + process.emitWarning = emitWarning + throw error + } + } catch (error) { + // fallback to polyfill implementation + Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js')) + } +} + +try { + // Don't use node: prefix for this, require+node: is not supported until node v14.14 + // Only `import()` can use prefix in 12.20 and later + const { Blob } = require('buffer') + if (Blob && !Blob.prototype.stream) { + Blob.prototype.stream = function name (params) { + let position = 0 + const blob = this + + return new ReadableStream({ + type: 'bytes', + async pull (ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + ctrl.enqueue(new Uint8Array(buffer)) + + if (position === blob.size) { + ctrl.close() + } + } + }) + } + } +} catch (error) {} +/* c8 ignore end */ diff --git a/src/libMPC/node_modules/formdata-polyfill/FormData.js b/src/libMPC/node_modules/formdata-polyfill/FormData.js new file mode 100644 index 0000000..8e73660 --- /dev/null +++ b/src/libMPC/node_modules/formdata-polyfill/FormData.js @@ -0,0 +1,441 @@ +/* formdata-polyfill. MIT License. Jimmy Wärting */ + +/* global FormData self Blob File */ +/* eslint-disable no-inner-declarations */ + +if (typeof Blob !== 'undefined' && (typeof FormData === 'undefined' || !FormData.prototype.keys)) { + const global = typeof globalThis === 'object' + ? globalThis + : typeof window === 'object' + ? window + : typeof self === 'object' ? self : this + + // keep a reference to native implementation + const _FormData = global.FormData + + // To be monkey patched + const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send + const _fetch = global.Request && global.fetch + const _sendBeacon = global.navigator && global.navigator.sendBeacon + // Might be a worker thread... + const _match = global.Element && global.Element.prototype + + // Unable to patch Request/Response constructor correctly #109 + // only way is to use ES6 class extend + // https://github.com/babel/babel/issues/1966 + + const stringTag = global.Symbol && Symbol.toStringTag + + // Add missing stringTags to blob and files + if (stringTag) { + if (!Blob.prototype[stringTag]) { + Blob.prototype[stringTag] = 'Blob' + } + + if ('File' in global && !File.prototype[stringTag]) { + File.prototype[stringTag] = 'File' + } + } + + // Fix so you can construct your own File + try { + new File([], '') // eslint-disable-line + } catch (a) { + global.File = function File (b, d, c) { + const blob = new Blob(b, c || {}) + const t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date() + + Object.defineProperties(blob, { + name: { + value: d + }, + lastModified: { + value: +t + }, + toString: { + value () { + return '[object File]' + } + } + }) + + if (stringTag) { + Object.defineProperty(blob, stringTag, { + value: 'File' + }) + } + + return blob + } + } + + function ensureArgs (args, expected) { + if (args.length < expected) { + throw new TypeError(`${expected} argument required, but only ${args.length} present.`) + } + } + + /** + * @param {string} name + * @param {string | undefined} filename + * @returns {[string, File|string]} + */ + function normalizeArgs (name, value, filename) { + if (value instanceof Blob) { + filename = filename !== undefined + ? String(filename + '') + : typeof value.name === 'string' + ? value.name + : 'blob' + + if (value.name !== filename || Object.prototype.toString.call(value) === '[object Blob]') { + value = new File([value], filename) + } + return [String(name), value] + } + return [String(name), String(value)] + } + + // normalize line feeds for textarea + // https://html.spec.whatwg.org/multipage/form-elements.html#textarea-line-break-normalisation-transformation + function normalizeLinefeeds (value) { + return value.replace(/\r?\n|\r/g, '\r\n') + } + + /** + * @template T + * @param {ArrayLike} arr + * @param {{ (elm: T): void; }} cb + */ + function each (arr, cb) { + for (let i = 0; i < arr.length; i++) { + cb(arr[i]) + } + } + + const escape = str => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + + /** + * @implements {Iterable} + */ + class FormDataPolyfill { + /** + * FormData class + * + * @param {HTMLFormElement=} form + */ + constructor (form) { + /** @type {[string, string|File][]} */ + this._data = [] + + const self = this + form && each(form.elements, (/** @type {HTMLInputElement} */ elm) => { + if ( + !elm.name || + elm.disabled || + elm.type === 'submit' || + elm.type === 'button' || + elm.matches('form fieldset[disabled] *') + ) return + + if (elm.type === 'file') { + const files = elm.files && elm.files.length + ? elm.files + : [new File([], '', { type: 'application/octet-stream' })] // #78 + + each(files, file => { + self.append(elm.name, file) + }) + } else if (elm.type === 'select-multiple' || elm.type === 'select-one') { + each(elm.options, opt => { + !opt.disabled && opt.selected && self.append(elm.name, opt.value) + }) + } else if (elm.type === 'checkbox' || elm.type === 'radio') { + if (elm.checked) self.append(elm.name, elm.value) + } else { + const value = elm.type === 'textarea' ? normalizeLinefeeds(elm.value) : elm.value + self.append(elm.name, value) + } + }) + } + + /** + * Append a field + * + * @param {string} name field name + * @param {string|Blob|File} value string / blob / file + * @param {string=} filename filename to use with blob + * @return {undefined} + */ + append (name, value, filename) { + ensureArgs(arguments, 2) + this._data.push(normalizeArgs(name, value, filename)) + } + + /** + * Delete all fields values given name + * + * @param {string} name Field name + * @return {undefined} + */ + delete (name) { + ensureArgs(arguments, 1) + const result = [] + name = String(name) + + each(this._data, entry => { + entry[0] !== name && result.push(entry) + }) + + this._data = result + } + + /** + * Iterate over all fields as [name, value] + * + * @return {Iterator} + */ + * entries () { + for (var i = 0; i < this._data.length; i++) { + yield this._data[i] + } + } + + /** + * Iterate over all fields + * + * @param {Function} callback Executed for each item with parameters (value, name, thisArg) + * @param {Object=} thisArg `this` context for callback function + */ + forEach (callback, thisArg) { + ensureArgs(arguments, 1) + for (const [name, value] of this) { + callback.call(thisArg, value, name, this) + } + } + + /** + * Return first field value given name + * or null if non existent + * + * @param {string} name Field name + * @return {string|File|null} value Fields value + */ + get (name) { + ensureArgs(arguments, 1) + const entries = this._data + name = String(name) + for (let i = 0; i < entries.length; i++) { + if (entries[i][0] === name) { + return entries[i][1] + } + } + return null + } + + /** + * Return all fields values given name + * + * @param {string} name Fields name + * @return {Array} [{String|File}] + */ + getAll (name) { + ensureArgs(arguments, 1) + const result = [] + name = String(name) + each(this._data, data => { + data[0] === name && result.push(data[1]) + }) + + return result + } + + /** + * Check for field name existence + * + * @param {string} name Field name + * @return {boolean} + */ + has (name) { + ensureArgs(arguments, 1) + name = String(name) + for (let i = 0; i < this._data.length; i++) { + if (this._data[i][0] === name) { + return true + } + } + return false + } + + /** + * Iterate over all fields name + * + * @return {Iterator} + */ + * keys () { + for (const [name] of this) { + yield name + } + } + + /** + * Overwrite all values given name + * + * @param {string} name Filed name + * @param {string} value Field value + * @param {string=} filename Filename (optional) + */ + set (name, value, filename) { + ensureArgs(arguments, 2) + name = String(name) + /** @type {[string, string|File][]} */ + const result = [] + const args = normalizeArgs(name, value, filename) + let replace = true + + // - replace the first occurrence with same name + // - discards the remaining with same name + // - while keeping the same order items where added + each(this._data, data => { + data[0] === name + ? replace && (replace = !result.push(args)) + : result.push(data) + }) + + replace && result.push(args) + + this._data = result + } + + /** + * Iterate over all fields + * + * @return {Iterator} + */ + * values () { + for (const [, value] of this) { + yield value + } + } + + /** + * Return a native (perhaps degraded) FormData with only a `append` method + * Can throw if it's not supported + * + * @return {FormData} + */ + ['_asNative'] () { + const fd = new _FormData() + + for (const [name, value] of this) { + fd.append(name, value) + } + + return fd + } + + /** + * [_blob description] + * + * @return {Blob} [description] + */ + ['_blob'] () { + const boundary = '----formdata-polyfill-' + Math.random(), + chunks = [], + p = `--${boundary}\r\nContent-Disposition: form-data; name="` + this.forEach((value, name) => typeof value == 'string' + ? chunks.push(p + escape(normalizeLinefeeds(name)) + `"\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + : chunks.push(p + escape(normalizeLinefeeds(name)) + `"; filename="${escape(value.name)}"\r\nContent-Type: ${value.type||"application/octet-stream"}\r\n\r\n`, value, `\r\n`)) + chunks.push(`--${boundary}--`) + return new Blob(chunks, { + type: "multipart/form-data; boundary=" + boundary + }) + } + + /** + * The class itself is iterable + * alias for formdata.entries() + * + * @return {Iterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Create the default string description. + * + * @return {string} [object FormData] + */ + toString () { + return '[object FormData]' + } + } + + if (_match && !_match.matches) { + _match.matches = + _match.matchesSelector || + _match.mozMatchesSelector || + _match.msMatchesSelector || + _match.oMatchesSelector || + _match.webkitMatchesSelector || + function (s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s) + var i = matches.length + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1 + } + } + + if (stringTag) { + /** + * Create the default string description. + * It is accessed internally by the Object.prototype.toString(). + */ + FormDataPolyfill.prototype[stringTag] = 'FormData' + } + + // Patch xhr's send method to call _blob transparently + if (_send) { + const setRequestHeader = global.XMLHttpRequest.prototype.setRequestHeader + + global.XMLHttpRequest.prototype.setRequestHeader = function (name, value) { + setRequestHeader.call(this, name, value) + if (name.toLowerCase() === 'content-type') this._hasContentType = true + } + + global.XMLHttpRequest.prototype.send = function (data) { + // need to patch send b/c old IE don't send blob's type (#44) + if (data instanceof FormDataPolyfill) { + const blob = data['_blob']() + if (!this._hasContentType) this.setRequestHeader('Content-Type', blob.type) + _send.call(this, blob) + } else { + _send.call(this, data) + } + } + } + + // Patch fetch's function to call _blob transparently + if (_fetch) { + global.fetch = function (input, init) { + if (init && init.body && init.body instanceof FormDataPolyfill) { + init.body = init.body['_blob']() + } + + return _fetch.call(this, input, init) + } + } + + // Patch navigator.sendBeacon to use native FormData + if (_sendBeacon) { + global.navigator.sendBeacon = function (url, data) { + if (data instanceof FormDataPolyfill) { + data = data['_asNative']() + } + return _sendBeacon.call(this, url, data) + } + } + + global['FormData'] = FormDataPolyfill +} diff --git a/src/libMPC/node_modules/formdata-polyfill/LICENSE b/src/libMPC/node_modules/formdata-polyfill/LICENSE new file mode 100644 index 0000000..fd0f555 --- /dev/null +++ b/src/libMPC/node_modules/formdata-polyfill/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jimmy Karl Roland Wärting + +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. diff --git a/src/libMPC/node_modules/formdata-polyfill/README.md b/src/libMPC/node_modules/formdata-polyfill/README.md new file mode 100644 index 0000000..8355299 --- /dev/null +++ b/src/libMPC/node_modules/formdata-polyfill/README.md @@ -0,0 +1,145 @@ +### A `FormData` polyfill for the browser ...and a module for NodeJS (`New!`) + +```bash +npm install formdata-polyfill +``` + +The browser polyfill will likely have done its part already, and i hope you stop supporting old browsers c",)
+But NodeJS still laks a proper FormData
The good old form-data package is a very old and isn't spec compatible and dose some abnormal stuff to construct and read FormData instances that other http libraries are not happy about when it comes to follow the spec. + +### The NodeJS / ESM version +- The modular (~2.3 KiB minified uncompressed) version of this package is independent of any browser stuff and don't patch anything +- It's as pure/spec compatible as it possible gets the test are run by WPT. +- It's compatible with [node-fetch](https://github.com/node-fetch/node-fetch). +- It have higher platform dependencies as it uses classes, symbols, ESM & private fields +- Only dependency it has is [fetch-blob](https://github.com/node-fetch/fetch-blob) + +```js +// Node example +import fetch from 'node-fetch' +import File from 'fetch-blob/file.js' +import { fileFromSync } from 'fetch-blob/from.js' +import { FormData } from 'formdata-polyfill/esm.min.js' + +const file = fileFromSync('./README.md') +const fd = new FormData() + +fd.append('file-upload', new File(['abc'], 'hello-world.txt')) +fd.append('file-upload', file) + +// it's also possible to append file/blob look-a-like items +// if you have streams coming from other destinations +fd.append('file-upload', { + size: 123, + type: '', + name: 'cat-video.mp4', + stream() { return stream }, + [Symbol.toStringTag]: 'File' +}) + +fetch('https://httpbin.org/post', { method: 'POST', body: fd }) +``` + +---- + +It also comes with way to convert FormData into Blobs - it's not something that every developer should have to deal with. +It's mainly for [node-fetch](https://github.com/node-fetch/node-fetch) and other http library to ease the process of serializing a FormData into a blob and just wish to deal with Blobs instead (Both Deno and Undici adapted a version of this [formDataToBlob](https://github.com/jimmywarting/FormData/blob/5ddea9e0de2fc5e246ab1b2f9d404dee0c319c02/formdata-to-blob.js) to the core and passes all WPT tests run by the browser itself) +```js +import { Readable } from 'node:stream' +import { FormData, formDataToBlob } from 'formdata-polyfill/esm.min.js' + +const blob = formDataToBlob(new FormData()) +fetch('https://httpbin.org/post', { method: 'POST', body: blob }) + +// node built in http and other similar http library have to do: +const stream = Readable.from(blob.stream()) +const req = http.request('http://httpbin.org/post', { + method: 'post', + headers: { + 'Content-Length': blob.size, + 'Content-Type': blob.type + } +}) +stream.pipe(req) +``` + +PS: blob & file that are appended to the FormData will not be read until any of the serialized blob read-methods gets called +...so uploading very large files is no biggie + +### Browser polyfill + +usage: + +```js +import 'formdata-polyfill' // that's it +``` + +The browser polyfill conditionally replaces the native implementation rather than fixing the missing functions, +since otherwise there is no way to get or delete existing values in the FormData object. +Therefore this also patches `XMLHttpRequest.prototype.send` and `fetch` to send the `FormData` as a blob, +and `navigator.sendBeacon` to send native `FormData`. + +I was unable to patch the Response/Request constructor +so if you are constructing them with FormData then you need to call `fd._blob()` manually. + +```js +new Request(url, { + method: 'post', + body: fd._blob ? fd._blob() : fd +}) +``` + +Dependencies +--- + +If you need to support IE <= 9 then I recommend you to include eligrey's [blob.js] +(which i hope you don't - since IE is now dead) + +
+ Updating from 2.x to 3.x + +Previously you had to import the polyfill and use that, +since it didn't replace the global (existing) FormData implementation. +But now it transparently calls `_blob()` for you when you are sending something with fetch or XHR, +by way of monkey-patching the `XMLHttpRequest.prototype.send` and `fetch` functions. + +So you maybe had something like this: + +```javascript +var FormData = require('formdata-polyfill') +var fd = new FormData(form) +xhr.send(fd._blob()) +``` + +There is no longer anything exported from the module +(though you of course still need to import it to install the polyfill), +so you can now use the FormData object as normal: + +```javascript +require('formdata-polyfill') +var fd = new FormData(form) +xhr.send(fd) +``` + +
+ + + +Native Browser compatibility (as of 2021-05-08) +--- +Based on this you can decide for yourself if you need this polyfill. + +[![screenshot](https://user-images.githubusercontent.com/1148376/117550329-0993aa80-b040-11eb-976c-14e31f1a3ba4.png)](https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility) + + + +This normalizes support for the FormData API: + + - `append` with filename + - `delete()`, `get()`, `getAll()`, `has()`, `set()` + - `entries()`, `keys()`, `values()`, and support for `for...of` + - Available in web workers (just include the polyfill) + + [npm-image]: https://img.shields.io/npm/v/formdata-polyfill.svg + [npm-url]: https://www.npmjs.com/package/formdata-polyfill + [blob.js]: https://github.com/eligrey/Blob.js diff --git a/src/libMPC/node_modules/formdata-polyfill/esm.min.d.ts b/src/libMPC/node_modules/formdata-polyfill/esm.min.d.ts new file mode 100644 index 0000000..b45f42e --- /dev/null +++ b/src/libMPC/node_modules/formdata-polyfill/esm.min.d.ts @@ -0,0 +1,5 @@ +export declare const FormData: { + new (): FormData; + prototype: FormData; +}; +export declare function formDataToBlob(formData: FormData): Blob; diff --git a/src/libMPC/node_modules/formdata-polyfill/esm.min.js b/src/libMPC/node_modules/formdata-polyfill/esm.min.js new file mode 100644 index 0000000..745ca29 --- /dev/null +++ b/src/libMPC/node_modules/formdata-polyfill/esm.min.js @@ -0,0 +1,40 @@ +/*! formdata-polyfill. MIT License. Jimmy Wärting */ + +import C from 'fetch-blob' +import F from 'fetch-blob/file.js' + +var {toStringTag:t,iterator:i,hasInstance:h}=Symbol, +r=Math.random, +m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), +f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']), +e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), +x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} +append(...a){x('append',arguments,2);this.#d.push(f(...a))} +delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)} +get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b} +has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} +forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)} +set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b} +*entries(){yield*this.#d} +*keys(){for(var[a]of this)yield a} +*values(){for(var[,a]of this)yield a}} + +/** @param {FormData} F */ +export function formDataToBlob (F,B=C){ +var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="` +F.forEach((v,n)=>typeof v=='string' +?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? */ + +const escape = (str, filename) => + (filename ? str : str.replace(/\r?\n|\r/g, '\r\n')) + .replace(/\n/g, '%0A') + .replace(/\r/g, '%0D') + .replace(/"/g, '%22') + +/** + * pure function to convert any formData instance to a Blob + * instances synchronous without reading all of the files + * + * @param {FormData|*} formData an instance of a formData Class + * @param {Blob|*} [BlobClass=Blob] the Blob class to use when constructing it + */ +export function formDataToBlob (formData, BlobClass = Blob) { + const boundary = ('----formdata-polyfill-' + Math.random()) + const chunks = [] + const prefix = `--${boundary}\r\nContent-Disposition: form-data; name="` + + for (let [name, value] of formData) { + if (typeof value === 'string') { + chunks.push(prefix + escape(name) + `"\r\n\r\n${value.replace(/\r(?!\n)|(? */ +;(function(){var h;function l(a){var b=0;return function(){return b>>0)+"_",e=0;return b}); +r("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c=12.20.0" + }, + "keywords": [ + "formdata", + "fetch", + "node-fetch", + "html5", + "browser", + "polyfill" + ], + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/FormData/issues" + }, + "homepage": "https://github.com/jimmywarting/FormData#readme", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "devDependencies": { + "@types/google-closure-compiler": "^0.0.19", + "@types/node": "^16.7.10", + "google-closure-compiler": "^20210808.0.0" + } +} diff --git a/src/libMPC/node_modules/hash-base/LICENSE b/src/libMPC/node_modules/hash-base/LICENSE new file mode 100644 index 0000000..6f02ae8 --- /dev/null +++ b/src/libMPC/node_modules/hash-base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Kirill Fomichev + +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. diff --git a/src/libMPC/node_modules/hash-base/README.md b/src/libMPC/node_modules/hash-base/README.md new file mode 100644 index 0000000..83ae2ed --- /dev/null +++ b/src/libMPC/node_modules/hash-base/README.md @@ -0,0 +1,48 @@ +# hash-base + +[![NPM Package](https://img.shields.io/npm/v/hash-base.svg?style=flat-square)](https://www.npmjs.org/package/hash-base) +[![Build Status](https://img.shields.io/travis/crypto-browserify/hash-base.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/hash-base) +[![Dependency status](https://img.shields.io/david/crypto-browserify/hash-base.svg?style=flat-square)](https://david-dm.org/crypto-browserify/hash-base#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Abstract base class to inherit from if you want to create streams implementing the same API as node crypto [Hash][1] (for [Cipher][2] / [Decipher][3] check [crypto-browserify/cipher-base][4]). + +## Example + +```js +const HashBase = require('hash-base') +const inherits = require('inherits') + +// our hash function is XOR sum of all bytes +function MyHash () { + HashBase.call(this, 1) // in bytes + + this._sum = 0x00 +} + +inherits(MyHash, HashBase) + +MyHash.prototype._update = function () { + for (let i = 0; i < this._block.length; ++i) this._sum ^= this._block[i] +} + +MyHash.prototype._digest = function () { + return this._sum +} + +const data = Buffer.from([ 0x00, 0x42, 0x01 ]) +const hash = new MyHash().update(data).digest() +console.log(hash) // => 67 +``` +You also can check [source code](index.js) or [crypto-browserify/md5.js][5] + +## LICENSE + +MIT + +[1]: https://nodejs.org/api/crypto.html#crypto_class_hash +[2]: https://nodejs.org/api/crypto.html#crypto_class_cipher +[3]: https://nodejs.org/api/crypto.html#crypto_class_decipher +[4]: https://github.com/crypto-browserify/cipher-base +[5]: https://github.com/crypto-browserify/md5.js diff --git a/src/libMPC/node_modules/hash-base/index.js b/src/libMPC/node_modules/hash-base/index.js new file mode 100644 index 0000000..059480b --- /dev/null +++ b/src/libMPC/node_modules/hash-base/index.js @@ -0,0 +1,95 @@ +'use strict' +var Buffer = require('safe-buffer').Buffer +var Transform = require('readable-stream').Transform +var inherits = require('inherits') + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase diff --git a/src/libMPC/node_modules/hash-base/package.json b/src/libMPC/node_modules/hash-base/package.json new file mode 100644 index 0000000..cfea6d4 --- /dev/null +++ b/src/libMPC/node_modules/hash-base/package.json @@ -0,0 +1,42 @@ +{ + "name": "hash-base", + "version": "3.1.0", + "description": "abstract base class for hash-streams", + "keywords": [ + "hash", + "stream" + ], + "homepage": "https://github.com/crypto-browserify/hash-base", + "bugs": { + "url": "https://github.com/crypto-browserify/hash-base/issues" + }, + "license": "MIT", + "author": "Kirill Fomichev (https://github.com/fanatid)", + "files": [ + "index.js" + ], + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/crypto-browserify/hash-base.git" + }, + "scripts": { + "coverage": "nyc node test/*.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "node test/*.js" + }, + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "safe-buffer": "^5.2.0" + }, + "devDependencies": { + "nyc": "^15.0.1", + "standard": "^14.3.3", + "tape": "^5.0.0" + }, + "engines": { + "node": ">=4" + } +} diff --git a/src/libMPC/node_modules/inherits/LICENSE b/src/libMPC/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/src/libMPC/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/src/libMPC/node_modules/inherits/README.md b/src/libMPC/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/src/libMPC/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/src/libMPC/node_modules/inherits/inherits.js b/src/libMPC/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/src/libMPC/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/src/libMPC/node_modules/inherits/inherits_browser.js b/src/libMPC/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/src/libMPC/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/src/libMPC/node_modules/inherits/package.json b/src/libMPC/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/src/libMPC/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/src/libMPC/node_modules/md5.js/LICENSE b/src/libMPC/node_modules/md5.js/LICENSE new file mode 100644 index 0000000..6f02ae8 --- /dev/null +++ b/src/libMPC/node_modules/md5.js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Kirill Fomichev + +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. diff --git a/src/libMPC/node_modules/md5.js/README.md b/src/libMPC/node_modules/md5.js/README.md new file mode 100644 index 0000000..36316e1 --- /dev/null +++ b/src/libMPC/node_modules/md5.js/README.md @@ -0,0 +1,29 @@ +# md5.js + +[![NPM Package](https://img.shields.io/npm/v/md5.js.svg?style=flat-square)](https://www.npmjs.org/package/md5.js) +[![Build Status](https://img.shields.io/travis/crypto-browserify/md5.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/md5.js) +[![Dependency status](https://img.shields.io/david/crypto-browserify/md5.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/md5.js#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Node style `md5` on pure JavaScript. + +From [NIST SP 800-131A][1]: *md5 is no longer acceptable where collision resistance is required such as digital signatures.* + +## Example + +```js +var MD5 = require('md5.js') + +console.log(new MD5().update('42').digest('hex')) +// => a1d0c6e83f027327d8461063f4ac58a6 + +var md5stream = new MD5() +md5stream.end('42') +console.log(md5stream.read().toString('hex')) +// => a1d0c6e83f027327d8461063f4ac58a6 +``` + +## LICENSE [MIT](LICENSE) + +[1]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf diff --git a/src/libMPC/node_modules/md5.js/index.js b/src/libMPC/node_modules/md5.js/index.js new file mode 100644 index 0000000..cbfa2e3 --- /dev/null +++ b/src/libMPC/node_modules/md5.js/index.js @@ -0,0 +1,146 @@ +'use strict' +var inherits = require('inherits') +var HashBase = require('hash-base') +var Buffer = require('safe-buffer').Buffer + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 diff --git a/src/libMPC/node_modules/md5.js/package.json b/src/libMPC/node_modules/md5.js/package.json new file mode 100644 index 0000000..e12e3c7 --- /dev/null +++ b/src/libMPC/node_modules/md5.js/package.json @@ -0,0 +1,38 @@ +{ + "name": "md5.js", + "version": "1.3.5", + "description": "node style md5 on pure JavaScript", + "keywords": [ + "crypto", + "md5" + ], + "homepage": "https://github.com/crypto-browserify/md5.js", + "bugs": { + "url": "https://github.com/crypto-browserify/md5.js/issues" + }, + "license": "MIT", + "author": "Kirill Fomichev (https://github.com/fanatid)", + "files": [ + "index.js" + ], + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/crypto-browserify/md5.js.git" + }, + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "node test/*.js" + }, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + }, + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "standard": "^7.0.0", + "tape": "^4.2.0" + } +} diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527203617.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527203617.md new file mode 100644 index 0000000..38d8f85 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527203617.md @@ -0,0 +1,2 @@ +# node-domexception +An implementation of the DOMException class from NodeJS diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527212714.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527212714.md new file mode 100644 index 0000000..eed1d13 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527212714.md @@ -0,0 +1,41 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMexception provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' + +hello().catch(err => { + if (err instanceof DOMException) { + ... + } +}) + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); +``` + +## APIs + +This package exposes two flavors of the `DOMException` interface depending on the imported module. + +### `domexception` module + +This module default-exports the `DOMException` interface constructor. + +### `domexception/webidl2js-wrapper` module + +This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527213345.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527213345.md new file mode 100644 index 0000000..5825416 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527213345.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527213411.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527213411.md new file mode 100644 index 0000000..4c21ec8 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527213411.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527213803.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527213803.md new file mode 100644 index 0000000..4cb8571 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527213803.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527214323.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527214323.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527214323.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/src/libMPC/node_modules/node-domexception/.history/README_20210527214408.md b/src/libMPC/node_modules/node-domexception/.history/README_20210527214408.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/README_20210527214408.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527203842.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527203842.js new file mode 100644 index 0000000..e69de29 diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527203947.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527203947.js new file mode 100644 index 0000000..b9a8b76 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527203947.js @@ -0,0 +1,8 @@ +const { MessageChannel } = require('worker_threads') + +if (!globalThis.DOMException) { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527204259.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527204259.js new file mode 100644 index 0000000..e9332a8 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527204259.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527204418.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527204418.js new file mode 100644 index 0000000..cb362cc --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527204418.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527204756.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527204756.js new file mode 100644 index 0000000..87d2655 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527204756.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527204833.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527204833.js new file mode 100644 index 0000000..837ebda --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527204833.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527211208.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527211208.js new file mode 100644 index 0000000..ba215ce --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527211208.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + var { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527211248.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527211248.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527211248.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527212722.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527212722.js new file mode 100644 index 0000000..91b3b52 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527212722.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527212731.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527212731.js new file mode 100644 index 0000000..cf28864 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527212731.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 2); diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527212746.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527212746.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527212746.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527212900.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527212900.js new file mode 100644 index 0000000..efa2442 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527212900.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527213022.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527213022.js new file mode 100644 index 0000000..e59f047 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527213022.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527213822.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527213822.js new file mode 100644 index 0000000..7f4e13d --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527213822.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527213843.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527213843.js new file mode 100644 index 0000000..ee75b73 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527213843.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527213852.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527213852.js new file mode 100644 index 0000000..a82bee3 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527213852.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527213910.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527213910.js new file mode 100644 index 0000000..1e1ca29 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527213910.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527214034.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527214034.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527214034.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527214643.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527214643.js new file mode 100644 index 0000000..92ed847 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527214643.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527214654.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527214654.js new file mode 100644 index 0000000..6d5cb8e --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527214654.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 21) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/src/libMPC/node_modules/node-domexception/.history/index_20210527214700.js b/src/libMPC/node_modules/node-domexception/.history/index_20210527214700.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/index_20210527214700.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527203733.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527203733.json new file mode 100644 index 0000000..5eeb306 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527203733.json @@ -0,0 +1,19 @@ +{ + "name": "domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527203825.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527203825.json new file mode 100644 index 0000000..4ca1713 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527203825.json @@ -0,0 +1,16 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527204621.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527204621.json new file mode 100644 index 0000000..3c414e9 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527204621.json @@ -0,0 +1,19 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527204913.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527204913.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527204913.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527204925.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527204925.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527204925.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527205145.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527205145.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527205145.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/src/libMPC/node_modules/node-domexception/.history/package_20210527205156.json b/src/libMPC/node_modules/node-domexception/.history/package_20210527205156.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/package_20210527205156.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/src/libMPC/node_modules/node-domexception/.history/test_20210527205603.js b/src/libMPC/node_modules/node-domexception/.history/test_20210527205603.js new file mode 100644 index 0000000..e69de29 diff --git a/src/libMPC/node_modules/node-domexception/.history/test_20210527205957.js b/src/libMPC/node_modules/node-domexception/.history/test_20210527205957.js new file mode 100644 index 0000000..73feac5 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/test_20210527205957.js @@ -0,0 +1,3 @@ +require('./index.js') + +console.log(DOMException.INDEX_SIZE_ERR) diff --git a/src/libMPC/node_modules/node-domexception/.history/test_20210527210021.js b/src/libMPC/node_modules/node-domexception/.history/test_20210527210021.js new file mode 100644 index 0000000..be47491 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/.history/test_20210527210021.js @@ -0,0 +1,3 @@ +const e = require('./index.js') + +console.log(e.INDEX_SIZE_ERR) diff --git a/src/libMPC/node_modules/node-domexception/LICENSE b/src/libMPC/node_modules/node-domexception/LICENSE new file mode 100644 index 0000000..bc8ceb7 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Jimmy Wärting + +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. diff --git a/src/libMPC/node_modules/node-domexception/README.md b/src/libMPC/node_modules/node-domexception/README.md new file mode 100644 index 0000000..a369461 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/README.md @@ -0,0 +1,46 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the legacy codes) + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` + +# Background + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws a DOMException and catch the constructor. This is exactly what this package dose for you and exposes it.
+This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
+The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +The DOMException is used in many places such as the Fetch API, File & Blobs, PostMessaging and more.
+Why they decided to call it **DOM**, I don't know + +Please consider sponsoring if you find this helpful diff --git a/src/libMPC/node_modules/node-domexception/index.js b/src/libMPC/node_modules/node-domexception/index.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/index.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/src/libMPC/node_modules/node-domexception/package.json b/src/libMPC/node_modules/node-domexception/package.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/src/libMPC/node_modules/node-domexception/package.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/src/libMPC/node_modules/node-fetch/@types/index.d.ts b/src/libMPC/node_modules/node-fetch/@types/index.d.ts new file mode 100644 index 0000000..274ca03 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/@types/index.d.ts @@ -0,0 +1,219 @@ +/// + +import {RequestOptions} from 'http'; +import {FormData} from 'formdata-polyfill/esm.min.js'; +import { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync +} from 'fetch-blob/from.js'; + +type AbortSignal = { + readonly aborted: boolean; + + addEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void; + removeEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void; +}; + +export type HeadersInit = Headers | Record | Iterable | Iterable>; + +export { + FormData, + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync +}; + +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. + * These actions include retrieving, setting, adding to, and removing. + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. + * You can add to this using methods like append() (see Examples.) + * In all methods of this interface, header names are matched by case-insensitive byte sequence. + * */ +export class Headers { + constructor(init?: HeadersInit); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach( + callbackfn: (value: string, key: string, parent: Headers) => void, + thisArg?: any + ): void; + + [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all key/value pairs contained in this object. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. + */ + keys(): IterableIterator; + /** + * Returns an iterator allowing to go through all values of the key/value pairs contained in this object. + */ + values(): IterableIterator; + + /** Node-fetch extension */ + raw(): Record; +} + +export interface RequestInit { + /** + * A BodyInit object or null to set request's body. + */ + body?: BodyInit | null; + /** + * A Headers object, an object literal, or an array of two-item arrays to set request's headers. + */ + headers?: HeadersInit; + /** + * A string to set request's method. + */ + method?: string; + /** + * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. + */ + redirect?: RequestRedirect; + /** + * An AbortSignal to set request's signal. + */ + signal?: AbortSignal | null; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer. + */ + referrer?: string; + /** + * A referrer policy to set request’s referrerPolicy. + */ + referrerPolicy?: ReferrerPolicy; + + // Node-fetch extensions to the whatwg/fetch spec + agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']); + compress?: boolean; + counter?: number; + follow?: number; + hostname?: string; + port?: number; + protocol?: string; + size?: number; + highWaterMark?: number; + insecureHTTPParser?: boolean; +} + +export interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +export type BodyInit = + | Blob + | Buffer + | URLSearchParams + | FormData + | NodeJS.ReadableStream + | string; +declare class BodyMixin { + constructor(body?: BodyInit, options?: {size?: number}); + + readonly body: NodeJS.ReadableStream | null; + readonly bodyUsed: boolean; + readonly size: number; + + /** @deprecated Use `body.arrayBuffer()` instead. */ + buffer(): Promise; + arrayBuffer(): Promise; + formData(): Promise; + blob(): Promise; + json(): Promise; + text(): Promise; +} + +// `Body` must not be exported as a class since it's not exported from the JavaScript code. +export interface Body extends Pick {} + +export type RequestRedirect = 'error' | 'follow' | 'manual'; +export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; +export type RequestInfo = string | Request; +export class Request extends BodyMixin { + constructor(input: URL | RequestInfo, init?: RequestInit); + + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + */ + readonly headers: Headers; + /** + * Returns request's HTTP method, which is "GET" by default. + */ + readonly method: string; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + */ + readonly redirect: RequestRedirect; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + */ + readonly signal: AbortSignal; + /** + * Returns the URL of request as a string. + */ + readonly url: string; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer. + */ + readonly referrer: string; + /** + * A referrer policy to set request’s referrerPolicy. + */ + readonly referrerPolicy: ReferrerPolicy; + clone(): Request; +} + +type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'; + +export class Response extends BodyMixin { + constructor(body?: BodyInit | null, init?: ResponseInit); + + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; + + static error(): Response; + static redirect(url: string, status?: number): Response; + static json(data: any, init?: ResponseInit): Response; +} + +export class FetchError extends Error { + constructor(message: string, type: string, systemError?: Record); + + name: 'FetchError'; + [Symbol.toStringTag]: 'FetchError'; + type: string; + code?: string; + errno?: string; +} + +export class AbortError extends Error { + type: string; + name: 'AbortError'; + [Symbol.toStringTag]: 'AbortError'; +} + +export function isRedirect(code: number): boolean; +export default function fetch(url: URL | RequestInfo, init?: RequestInit): Promise; diff --git a/src/libMPC/node_modules/node-fetch/LICENSE.md b/src/libMPC/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..41ca1b6 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 - 2020 Node Fetch Team + +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. + diff --git a/src/libMPC/node_modules/node-fetch/README.md b/src/libMPC/node_modules/node-fetch/README.md new file mode 100644 index 0000000..badc2b1 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/README.md @@ -0,0 +1,872 @@ +
+ Node Fetch +
+

A light-weight module that brings Fetch API to Node.js.

+ Build status + Coverage status + Current version + Install size + Mentioned in Awesome Node.js + Discord +
+
+ Consider supporting us on our Open Collective: +
+
+ Open Collective +
+ +--- + +**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)** + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Upgrading](#upgrading) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) + - [Handling cookies](#handling-cookies) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file](#post-data-using-a-file) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Default Headers](#default-headers) + - [Custom Agent](#custom-agent) + - [Custom highWaterMark](#custom-highwatermark) + - [Insecure HTTP Parser](#insecure-http-parser) + - [Class: Request](#class-request) + - [new Request(input[, options])](#new-requestinput-options) + - [Class: Response](#class-response) + - [new Response([body[, options]])](#new-responsebody-options) + - [response.ok](#responseok) + - [response.redirected](#responseredirected) + - [response.type](#responsetype) + - [Class: Headers](#class-headers) + - [new Headers([init])](#new-headersinit) + - [Interface: Body](#interface-body) + - [body.body](#bodybody) + - [body.bodyUsed](#bodybodyused) + - [body.arrayBuffer()](#bodyarraybuffer) + - [body.blob()](#bodyblob) + - [body.formData()](#formdata) + - [body.json()](#bodyjson) + - [body.text()](#bodytext) + - [Class: FetchError](#class-fetcherror) + - [Class: AbortError](#class-aborterror) +- [TypeScript](#typescript) +- [Acknowledgement](#acknowledgement) +- [Team](#team) + - [Former](#former) +- [License](#license) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise and async functions. +- Use native Node streams for body, on both request and response. +- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting. + +## Difference from client-side fetch + +- See known differences: + - [As of v3.x](docs/v3-LIMITS.md) + - [As of v2.x](docs/v2-LIMITS.md) +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`3.x`) requires at least Node.js 12.20.0. + +```sh +npm install node-fetch +``` + +## Loading and configuring the module + +### ES Modules (ESM) + +```js +import fetch from 'node-fetch'; +``` + +### CommonJS + +`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`. + +If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2. + +```sh +npm install node-fetch@2 +``` + +Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously: + +```js +// mod.cjs +const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args)); +``` + +### Providing global access + +To use `fetch()` without importing it, you can patch the `global` object in node: + +```js +// fetch-polyfill.js +import fetch, { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync, + FormData, + Headers, + Request, + Response, +} from 'node-fetch' + +if (!globalThis.fetch) { + globalThis.fetch = fetch + globalThis.Headers = Headers + globalThis.Request = Request + globalThis.Response = Response +} + +// index.js +import './fetch-polyfill' + +// ... +``` + +## Upgrading + +Using an old version of node-fetch? Check out the following files: + +- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md) +- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md) +- [Changelog](https://github.com/node-fetch/node-fetch/releases) + +## Common Usage + +NOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading). + +### Plain text or HTML + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://github.com/'); +const body = await response.text(); + +console.log(body); +``` + +### JSON + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://api.github.com/users/github'); +const data = await response.json(); + +console.log(data); +``` + +### Simple Post + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'}); +const data = await response.json(); + +console.log(data); +``` + +### Post with JSON + +```js +import fetch from 'node-fetch'; + +const body = {a: 1}; + +const response = await fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: {'Content-Type': 'application/json'} +}); +const data = await response.json(); + +console.log(data); +``` + +### Post with form parameters + +`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +import fetch from 'node-fetch'; + +const params = new URLSearchParams(); +params.append('a', 1); + +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params}); +const data = await response.json(); + +console.log(data); +``` + +### Handling exceptions + +NOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section. + +Wrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details. + +```js +import fetch from 'node-fetch'; + +try { + await fetch('https://domain.invalid/'); +} catch (error) { + console.log(error); +} +``` + +### Handling client and server errors + +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +import fetch from 'node-fetch'; + +class HTTPResponseError extends Error { + constructor(response) { + super(`HTTP Error Response: ${response.status} ${response.statusText}`); + this.response = response; + } +} + +const checkStatus = response => { + if (response.ok) { + // response.status >= 200 && response.status < 300 + return response; + } else { + throw new HTTPResponseError(response); + } +} + +const response = await fetch('https://httpbin.org/status/400'); + +try { + checkStatus(response); +} catch (error) { + console.error(error); + + const errorBody = await error.response.text(); + console.error(`Error body: ${errorBody}`); +} +``` + +### Handling cookies + +Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details. + +## Advanced Usage + +### Streams + +The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete. + +```js +import {createWriteStream} from 'node:fs'; +import {pipeline} from 'node:stream'; +import {promisify} from 'node:util' +import fetch from 'node-fetch'; + +const streamPipeline = promisify(pipeline); + +const response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png'); + +if (!response.ok) throw new Error(`unexpected response ${response.statusText}`); + +await streamPipeline(response.body, createWriteStream('./octocat.png')); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://httpbin.org/stream/3'); + +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +import fetch from 'node-fetch'; + +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; + +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +### Accessing Headers and other Metadata + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://github.com/'); + +console.log(response.ok); +console.log(response.status); +console.log(response.statusText); +console.log(response.headers.raw()); +console.log(response.headers.get('content-type')); +``` + +### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com'); + +// Returns an array of values, instead of a string of comma-separated values +console.log(response.headers.raw()['set-cookie']); +``` + +### Post data using a file + +```js +import fetch, { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync, +} from 'node-fetch' + +const mimetype = 'text/plain' +const blob = fileFromSync('./input.txt', mimetype) +const url = 'https://httpbin.org/post' + +const response = await fetch(url, { method: 'POST', body: blob }) +const data = await response.json() + +console.log(data) +``` + +node-fetch comes with a spec-compliant [FormData] implementations for posting +multipart/form-data payloads + +```js +import fetch, { FormData, File, fileFrom } from 'node-fetch' + +const httpbin = 'https://httpbin.org/post' +const formData = new FormData() +const binary = new Uint8Array([ 97, 98, 99 ]) +const abc = new File([binary], 'abc.txt', { type: 'text/plain' }) + +formData.set('greeting', 'Hello, world!') +formData.set('file-upload', abc, 'new name.txt') + +const response = await fetch(httpbin, { method: 'POST', body: formData }) +const data = await response.json() + +console.log(data) +``` + +If you for some reason need to post a stream coming from any arbitrary place, +then you can append a [Blob] or a [File] look-a-like item. + +The minimum requirement is that it has: +1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File` +2. A known size. +3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer. + +The `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer) +so Node.Readable streams and whatwg streams works just fine. + +```js +formData.append('upload', { + [Symbol.toStringTag]: 'Blob', + size: 3, + *stream() { + yield new Uint8Array([97, 98, 99]) + }, + arrayBuffer() { + return new Uint8Array([97, 98, 99]).buffer + } +}, 'abc.txt') +``` + +### Request cancellation with AbortSignal + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import fetch, { AbortError } from 'node-fetch'; + +// AbortController was added in node v14.17.0 globally +const AbortController = globalThis.AbortController || await import('abort-controller') + +const controller = new AbortController(); +const timeout = setTimeout(() => { + controller.abort(); +}, 150); + +try { + const response = await fetch('https://example.com', {signal: controller.signal}); + const data = await response.json(); +} catch (error) { + if (error instanceof AbortError) { + console.log('request was aborted'); + } +} finally { + clearTimeout(timeout); +} +``` + +See [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples. + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // Request body. can be null, or a Node.js Readable stream + redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // Pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null, // http(s).Agent instance or function that returns an instance (see below) + highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. + insecureHTTPParser: false // Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. +} +``` + +#### Default Headers + +If no values are set, the following request headers will be sent automatically: + +| Header | Value | +| ------------------- | ------------------------------------------------------ | +| `Accept-Encoding` | `gzip, deflate, br` (when `options.compress === true`) | +| `Accept` | `*/*` | +| `Content-Length` | _(automatically calculated, if possible)_ | +| `Host` | _(host and port information from the target URI)_ | +| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ | +| `User-Agent` | `node-fetch` | + + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +#### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +import http from 'node:http'; +import https from 'node:https'; + +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function(_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +}; +``` + + + +#### Custom highWaterMark + +Stream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node. + +The recommended way to fix this problem is to resolve cloned response in parallel: + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com'); +const r1 = response.clone(); + +const results = await Promise.all([response.json(), r1.text()]); + +console.log(results[0]); +console.log(results[1]); +``` + +If for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option: + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com', { + // About 1MB + highWaterMark: 1024 * 1024 +}); + +const result = await res.clone().arrayBuffer(); +console.dir(result); +``` + +#### Insecure HTTP Parser + +Passed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information. + +#### Manual Redirect + +The `redirect: 'manual'` option for node-fetch is different from the browser & specification, which +results in an [opaque-redirect filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect). +node-fetch gives you the typical [basic filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-basic) instead. + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://httpbin.org/status/301', { redirect: 'manual' }); + +if (response.status === 301 || response.status === 302) { + const locationURL = new URL(response.headers.get('location'), response.url); + const response2 = await fetch(locationURL, { redirect: 'manual' }); + console.dir(response2); +} +``` + + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` +- `highWaterMark` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +_(spec-compliant)_ + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options](#fetch-options) for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `trailer` + +#### new Response([body[, options]]) + +_(spec-compliant)_ + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +_(spec-compliant)_ + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +_(spec-compliant)_ + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + +#### response.type + +_(deviation from spec)_ + +Convenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response). + + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +_(spec-compliant)_ + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class +import {Headers} from 'node-fetch'; + +const meta = { + 'Content-Type': 'text/xml' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [['Content-Type', 'text/xml']]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +#### body.body + +_(deviation from spec)_ + +- Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +_(spec-compliant)_ + +- `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() + +#### body.formData() + +#### body.blob() + +#### body.json() + +#### body.text() + +`fetch` comes with methods to parse `multipart/form-data` payloads as well as +`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that +Service Worker can intercept such messages before it's sent to the server to +alter them. This is useful for anybody building a server so you can use it to +parse & consume payloads. + +
+Code example + +```js +import http from 'node:http' +import { Response } from 'node-fetch' + +http.createServer(async function (req, res) { + const formData = await new Response(req, { + headers: req.headers // Pass along the boundary value + }).formData() + const allFields = [...formData] + + const file = formData.get('uploaded-files') + const arrayBuffer = await file.arrayBuffer() + const text = await file.text() + const whatwgReadableStream = file.stream() + + // other was to consume the request could be to do: + const json = await new Response(req).json() + const text = await new Response(req).text() + const arrayBuffer = await new Response(req).arrayBuffer() + const blob = await new Response(req, { + headers: req.headers // So that `type` inherits `Content-Type` + }.blob() +}) +``` + +
+ + + +### Class: FetchError + +_(node-fetch extension)_ + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + + +### Class: AbortError + +_(node-fetch extension)_ + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## TypeScript + +**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.** + +For older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped): + +```sh +npm install --save-dev @types/node-fetch@2.x +``` + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +## Team + +| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) | +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | +| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.ch) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) | + +###### Former + +- [Timothy Gu](https://github.com/timothygu) +- [Jared Kantrowitz](https://github.com/jkantr) + +## License + +[MIT](LICENSE.md) + +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md +[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData +[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob +[File]: https://developer.mozilla.org/en-US/docs/Web/API/File diff --git a/src/libMPC/node_modules/node-fetch/package.json b/src/libMPC/node_modules/node-fetch/package.json new file mode 100644 index 0000000..2b4e858 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/package.json @@ -0,0 +1,131 @@ +{ + "name": "node-fetch", + "version": "3.3.2", + "description": "A light-weight module that brings Fetch API to node.js", + "main": "./src/index.js", + "sideEffects": false, + "type": "module", + "files": [ + "src", + "@types/index.d.ts" + ], + "types": "./@types/index.d.ts", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "mocha", + "coverage": "c8 report --reporter=text-lcov | coveralls", + "test-types": "tsd", + "lint": "xo" + }, + "repository": { + "type": "git", + "url": "https://github.com/node-fetch/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/node-fetch/node-fetch/issues" + }, + "homepage": "https://github.com/node-fetch/node-fetch", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + }, + "devDependencies": { + "abort-controller": "^3.0.0", + "abortcontroller-polyfill": "^1.7.1", + "busboy": "^1.4.0", + "c8": "^7.7.2", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^3.0.2", + "chai-string": "^1.5.0", + "coveralls": "^3.1.0", + "form-data": "^4.0.0", + "formdata-node": "^4.2.4", + "mocha": "^9.1.3", + "p-timeout": "^5.0.0", + "stream-consumers": "^1.0.1", + "tsd": "^0.14.0", + "xo": "^0.39.1" + }, + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "tsd": { + "cwd": "@types", + "compilerOptions": { + "esModuleInterop": true + } + }, + "xo": { + "envs": [ + "node", + "browser" + ], + "ignores": [ + "example.js" + ], + "rules": { + "complexity": 0, + "import/extensions": 0, + "import/no-useless-path-segments": 0, + "import/no-anonymous-default-export": 0, + "import/no-named-as-default": 0, + "unicorn/import-index": 0, + "unicorn/no-array-reduce": 0, + "unicorn/prefer-node-protocol": 0, + "unicorn/numeric-separators-style": 0, + "unicorn/explicit-length-check": 0, + "capitalized-comments": 0, + "node/no-unsupported-features/es-syntax": 0, + "@typescript-eslint/member-ordering": 0 + }, + "overrides": [ + { + "files": "test/**/*.js", + "envs": [ + "node", + "mocha" + ], + "rules": { + "max-nested-callbacks": 0, + "no-unused-expressions": 0, + "no-warning-comments": 0, + "new-cap": 0, + "guard-for-in": 0, + "unicorn/no-array-for-each": 0, + "unicorn/prevent-abbreviations": 0, + "promise/prefer-await-to-then": 0, + "ava/no-import-test-files": 0 + } + } + ] + }, + "runkitExampleFilename": "example.js", + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/src/libMPC/node_modules/node-fetch/src/body.js b/src/libMPC/node_modules/node-fetch/src/body.js new file mode 100644 index 0000000..714e27e --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/body.js @@ -0,0 +1,397 @@ + +/** + * Body.js + * + * Body interface provides common methods for Request and Response + */ + +import Stream, {PassThrough} from 'node:stream'; +import {types, deprecate, promisify} from 'node:util'; +import {Buffer} from 'node:buffer'; + +import Blob from 'fetch-blob'; +import {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js'; + +import {FetchError} from './errors/fetch-error.js'; +import {FetchBaseError} from './errors/base.js'; +import {isBlob, isURLSearchParameters} from './utils/is.js'; + +const pipeline = promisify(Stream.pipeline); +const INTERNALS = Symbol('Body internals'); + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +export default class Body { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + + if (body === null) { + // Body is undefined or null + body = null; + } else if (isURLSearchParameters(body)) { + // Body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) { + // Body is blob + } else if (Buffer.isBuffer(body)) { + // Body is Buffer + } else if (types.isAnyArrayBuffer(body)) { + // Body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // Body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) { + // Body is stream + } else if (body instanceof FormData) { + // Body is FormData + body = formDataToBlob(body); + boundary = body.type.split('=')[1]; + } else { + // None of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + + let stream = body; + + if (Buffer.isBuffer(body)) { + stream = Stream.Readable.from(body); + } else if (isBlob(body)) { + stream = Stream.Readable.from(body.stream()); + } + + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + + if (body instanceof Stream) { + body.on('error', error_ => { + const error = error_ instanceof FetchBaseError ? + error_ : + new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); + this[INTERNALS].error = error; + }); + } + } + + get body() { + return this[INTERNALS].stream; + } + + get bodyUsed() { + return this[INTERNALS].disturbed; + } + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const {buffer, byteOffset, byteLength} = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + + async formData() { + const ct = this.headers.get('content-type'); + + if (ct.startsWith('application/x-www-form-urlencoded')) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + + for (const [name, value] of parameters) { + formData.append(name, value); + } + + return formData; + } + + const {toFormData} = await import('./utils/multipart-parser.js'); + return toFormData(this.body, ct); + } + + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || ''; + const buf = await this.arrayBuffer(); + + return new Blob([buf], { + type: ct + }); + } + + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +} + +Body.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: {enumerable: true}, + bodyUsed: {enumerable: true}, + arrayBuffer: {enumerable: true}, + blob: {enumerable: true}, + json: {enumerable: true}, + text: {enumerable: true}, + data: {get: deprecate(() => {}, + 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')} +}); + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + + data[INTERNALS].disturbed = true; + + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + + const {body} = data; + + // Body is null + if (body === null) { + return Buffer.alloc(0); + } + + /* c8 ignore next 3 */ + if (!(body instanceof Stream)) { + return Buffer.alloc(0); + } + + // Body is stream + // get ready to actually consume the body + const accum = []; + let accumBytes = 0; + + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size'); + body.destroy(error); + throw error; + } + + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error); + throw error_; + } + + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every(c => typeof c === 'string')) { + return Buffer.from(accum.join('')); + } + + return Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} + +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @param String highWaterMark highWaterMark for both PassThrough body streams + * @return Mixed + */ +export const clone = (instance, highWaterMark) => { + let p1; + let p2; + let {body} = instance[INTERNALS]; + + // Don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } + + // Check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) { + // Tee instance body + p1 = new PassThrough({highWaterMark}); + p2 = new PassThrough({highWaterMark}); + body.pipe(p1); + body.pipe(p2); + // Set instance body to teed body and return the other teed body + instance[INTERNALS].stream = p1; + body = p2; + } + + return body; +}; + +const getNonSpecFormDataBoundary = deprecate( + body => body.getBoundary(), + 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package', + 'https://github.com/node-fetch/node-fetch/issues/1167' +); + +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param {any} body Any options.body input + * @returns {string | null} + */ +export const extractContentType = (body, request) => { + // Body is null or undefined + if (body === null) { + return null; + } + + // Body is string + if (typeof body === 'string') { + return 'text/plain;charset=UTF-8'; + } + + // Body is a URLSearchParams + if (isURLSearchParameters(body)) { + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } + + // Body is blob + if (isBlob(body)) { + return body.type || null; + } + + // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView) + if (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; + } + + // Detect form data input from form-data module + if (body && typeof body.getBoundary === 'function') { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + + // Body is stream - can't really do much about this + if (body instanceof Stream) { + return null; + } + + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; +}; + +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param {any} obj.body Body object from the Body instance. + * @returns {number | null} + */ +export const getTotalBytes = request => { + const {body} = request[INTERNALS]; + + // Body is null or undefined + if (body === null) { + return 0; + } + + // Body is Blob + if (isBlob(body)) { + return body.size; + } + + // Body is Buffer + if (Buffer.isBuffer(body)) { + return body.length; + } + + // Detect form data input from form-data module + if (body && typeof body.getLengthSync === 'function') { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + + // Body is stream + return null; +}; + +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param {Stream.Writable} dest The stream to write to. + * @param obj.body Body object from the Body instance. + * @returns {Promise} + */ +export const writeToStream = async (dest, {body}) => { + if (body === null) { + // Body is null + dest.end(); + } else { + // Body is stream + await pipeline(body, dest); + } +}; diff --git a/src/libMPC/node_modules/node-fetch/src/errors/abort-error.js b/src/libMPC/node_modules/node-fetch/src/errors/abort-error.js new file mode 100644 index 0000000..0b62f1c --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/errors/abort-error.js @@ -0,0 +1,10 @@ +import {FetchBaseError} from './base.js'; + +/** + * AbortError interface for cancelled requests + */ +export class AbortError extends FetchBaseError { + constructor(message, type = 'aborted') { + super(message, type); + } +} diff --git a/src/libMPC/node_modules/node-fetch/src/errors/base.js b/src/libMPC/node_modules/node-fetch/src/errors/base.js new file mode 100644 index 0000000..4e66e1b --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/errors/base.js @@ -0,0 +1,17 @@ +export class FetchBaseError extends Error { + constructor(message, type) { + super(message); + // Hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); + + this.type = type; + } + + get name() { + return this.constructor.name; + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } +} diff --git a/src/libMPC/node_modules/node-fetch/src/errors/fetch-error.js b/src/libMPC/node_modules/node-fetch/src/errors/fetch-error.js new file mode 100644 index 0000000..f7ae5cc --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/errors/fetch-error.js @@ -0,0 +1,26 @@ + +import {FetchBaseError} from './base.js'; + +/** + * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError +*/ + +/** + * FetchError interface for operational errors + */ +export class FetchError extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code + if (systemError) { + // eslint-disable-next-line no-multi-assign + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +} diff --git a/src/libMPC/node_modules/node-fetch/src/headers.js b/src/libMPC/node_modules/node-fetch/src/headers.js new file mode 100644 index 0000000..cd69455 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/headers.js @@ -0,0 +1,267 @@ +/** + * Headers.js + * + * Headers class offers convenient helpers + */ + +import {types} from 'node:util'; +import http from 'node:http'; + +/* c8 ignore next 9 */ +const validateHeaderName = typeof http.validateHeaderName === 'function' ? + http.validateHeaderName : + name => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'}); + throw error; + } + }; + +/* c8 ignore next 9 */ +const validateHeaderValue = typeof http.validateHeaderValue === 'function' ? + http.validateHeaderValue : + (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'}); + throw error; + } + }; + +/** + * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit + */ + +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. + * These actions include retrieving, setting, adding to, and removing. + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. + * You can add to this using methods like append() (see Examples.) + * In all methods of this interface, header names are matched by case-insensitive byte sequence. + * + */ +export default class Headers extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + // Validate and normalize init object in [name, value(s)][] + /** @type {string[][]} */ + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map(value => [name, value])); + } + } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq + // No op + } else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + // eslint-disable-next-line no-eq-null, eqeqeq + if (method == null) { + // Record + result.push(...Object.entries(init)); + } else { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // Sequence> + // Note: per spec we have to first exhaust the lists then process them + result = [...init] + .map(pair => { + if ( + typeof pair !== 'object' || types.isBoxedPrimitive(pair) + ) { + throw new TypeError('Each header pair must be an iterable object'); + } + + return [...pair]; + }).map(pair => { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + + return [...pair]; + }); + } + } else { + throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)'); + } + + // Validate and lowercase + result = + result.length > 0 ? + result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : + undefined; + + super(result); + + // Returning a Proxy that will lowercase key names, validate parameters and sort keys + // eslint-disable-next-line no-constructor-return + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case 'append': + case 'set': + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + + case 'delete': + case 'has': + case 'getAll': + return name => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + + case 'keys': + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + + default: + return Reflect.get(target, p, receiver); + } + } + }); + /* c8 ignore next */ + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } + + toString() { + return Object.prototype.toString.call(this); + } + + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + + let value = values.join(', '); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + + return value; + } + + forEach(callback, thisArg = undefined) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + + * values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + + /** + * @type {() => IterableIterator<[string, string]>} + */ + * entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + + [Symbol.iterator]() { + return this.entries(); + } + + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for('nodejs.util.inspect.custom')]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + // Http.request() only supports string as Host header. + // This hack makes specifying custom Host header possible. + if (key === 'host') { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + + return result; + }, {}); + } +} + +/** + * Re-shaping object for Web IDL tests + * Only need to do it for overridden methods + */ +Object.defineProperties( + Headers.prototype, + ['get', 'entries', 'forEach', 'values'].reduce((result, property) => { + result[property] = {enumerable: true}; + return result; + }, {}) +); + +/** + * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do + * not conform to HTTP grammar productions. + * @param {import('http').IncomingMessage['rawHeaders']} headers + */ +export function fromRawHeaders(headers = []) { + return new Headers( + headers + // Split into pairs + .reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + + return result; + }, []) + .filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + + ); +} diff --git a/src/libMPC/node_modules/node-fetch/src/index.js b/src/libMPC/node_modules/node-fetch/src/index.js new file mode 100644 index 0000000..7c4aee8 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/index.js @@ -0,0 +1,417 @@ +/** + * Index.js + * + * a request API compatible with window.fetch + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + +import http from 'node:http'; +import https from 'node:https'; +import zlib from 'node:zlib'; +import Stream, {PassThrough, pipeline as pump} from 'node:stream'; +import {Buffer} from 'node:buffer'; + +import dataUriToBuffer from 'data-uri-to-buffer'; + +import {writeToStream, clone} from './body.js'; +import Response from './response.js'; +import Headers, {fromRawHeaders} from './headers.js'; +import Request, {getNodeRequestOptions} from './request.js'; +import {FetchError} from './errors/fetch-error.js'; +import {AbortError} from './errors/abort-error.js'; +import {isRedirect} from './utils/is-redirect.js'; +import {FormData} from 'formdata-polyfill/esm.min.js'; +import {isDomainOrSubdomain, isSameProtocol} from './utils/is.js'; +import {parseReferrerPolicyFromHeader} from './utils/referrer.js'; +import { + Blob, + File, + fileFromSync, + fileFrom, + blobFromSync, + blobFrom +} from 'fetch-blob/from.js'; + +export {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect}; +export {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom}; + +const supportedSchemas = new Set(['data:', 'http:', 'https:']); + +/** + * Fetch function + * + * @param {string | URL | import('./request').default} url - Absolute url or Request instance + * @param {*} [options_] - Fetch options + * @return {Promise} + */ +export default async function fetch(url, options_) { + return new Promise((resolve, reject) => { + // Build request object + const request = new Request(url, options_); + const {parsedURL, options} = getNodeRequestOptions(request); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`); + } + + if (parsedURL.protocol === 'data:') { + const data = dataUriToBuffer(request.url); + const response = new Response(data, {headers: {'Content-Type': data.typeFull}}); + resolve(response); + return; + } + + // Wrap http.request into fetch + const send = (parsedURL.protocol === 'https:' ? https : http).request; + const {signal} = request; + let response = null; + + const abort = () => { + const error = new AbortError('The operation was aborted.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + + if (!response || !response.body) { + return; + } + + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = () => { + abort(); + finalize(); + }; + + // Send request + const request_ = send(parsedURL.toString(), options); + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener('abort', abortAndFinalize); + } + }; + + request_.on('error', error => { + reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error)); + finalize(); + }); + + fixResponseChunkedTransferBadEnding(request_, error => { + if (response && response.body) { + response.body.destroy(error); + } + }); + + /* c8 ignore next 18 */ + if (process.version < 'v14') { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + request_.on('socket', s => { + let endedWithEventsCount; + s.prependListener('end', () => { + endedWithEventsCount = s._eventsCount; + }); + s.prependListener('close', hadError => { + // if end happened before close but the socket didn't emit an error, do it now + if (response && endedWithEventsCount < s._eventsCount && !hadError) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', error); + } + }); + }); + } + + request_.on('response', response_ => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + + // HTTP fetch step 5 + if (isRedirect(response_.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request.url); + } catch { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // Nothing to do + break; + case 'follow': { + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOptions = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone(request), + signal: request.signal, + size: request.size, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy + }; + + // when forwarding sensitive headers like "Authorization", + // "WWW-Authenticate", and "Cookie" to untrusted targets, + // headers will be ignored when following a redirect to a domain + // that is not a subdomain match or exact match of the initial domain. + // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + // will forward the sensitive headers, but a redirect to "bar.com" will not. + // headers will also be ignored when following a redirect to a domain using + // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" + // will not forward the sensitive headers + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOptions.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) { + requestOptions.method = 'GET'; + requestOptions.body = undefined; + requestOptions.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 14 + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + + default: + return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); + } + } + + // Prepare response + if (signal) { + response_.once('end', () => { + signal.removeEventListener('abort', abortAndFinalize); + }); + } + + let body = pump(response_, new PassThrough(), error => { + if (error) { + reject(error); + } + }); + // see https://github.com/nodejs/node/pull/29376 + /* c8 ignore next 3 */ + if (process.version < 'v12.10') { + response_.on('aborted', abortAndFinalize); + } + + const responseOptions = { + url: request.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request.size, + counter: request.counter, + highWaterMark: request.highWaterMark + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // For gzip + if (codings === 'gzip' || codings === 'x-gzip') { + body = pump(body, zlib.createGunzip(zlibOptions), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For deflate + if (codings === 'deflate' || codings === 'x-deflate') { + // Handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = pump(response_, new PassThrough(), error => { + if (error) { + reject(error); + } + }); + raw.once('data', chunk => { + // See http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = pump(body, zlib.createInflate(), error => { + if (error) { + reject(error); + } + }); + } else { + body = pump(body, zlib.createInflateRaw(), error => { + if (error) { + reject(error); + } + }); + } + + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once('end', () => { + // Some old IIS servers return zero-length OK deflate responses, so + // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + + // For br + if (codings === 'br') { + body = pump(body, zlib.createBrotliDecompress(), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // Otherwise, use response as-is + response = new Response(body, responseOptions); + resolve(response); + }); + + // eslint-disable-next-line promise/prefer-await-to-then + writeToStream(request_, request).catch(reject); + }); +} + +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + const LAST_CHUNK = Buffer.from('0\r\n\r\n'); + + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + + request.on('response', response => { + const {headers} = response; + isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length']; + }); + + request.on('socket', socket => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(error); + } + }; + + const onData = buf => { + properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + + // Sometimes final 0-length chunk and end of message code are in separate packets + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = ( + Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 + ); + } + + previousChunk = buf; + }; + + socket.prependListener('close', onSocketClose); + socket.on('data', onData); + + request.on('close', () => { + socket.removeListener('close', onSocketClose); + socket.removeListener('data', onData); + }); + }); +} diff --git a/src/libMPC/node_modules/node-fetch/src/request.js b/src/libMPC/node_modules/node-fetch/src/request.js new file mode 100644 index 0000000..af2ebc8 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/request.js @@ -0,0 +1,313 @@ +/** + * Request.js + * + * Request class contains server only options + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + +import {format as formatUrl} from 'node:url'; +import {deprecate} from 'node:util'; +import Headers from './headers.js'; +import Body, {clone, extractContentType, getTotalBytes} from './body.js'; +import {isAbortSignal} from './utils/is.js'; +import {getSearch} from './utils/get-search.js'; +import { + validateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY +} from './utils/referrer.js'; + +const INTERNALS = Symbol('Request internals'); + +/** + * Check if `obj` is an instance of Request. + * + * @param {*} object + * @return {boolean} + */ +const isRequest = object => { + return ( + typeof object === 'object' && + typeof object[INTERNALS] === 'object' + ); +}; + +const doBadDataWarn = deprecate(() => {}, + '.data is not a valid RequestInit property, use .body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (request)'); + +/** + * Request class + * + * Ref: https://fetch.spec.whatwg.org/#request-class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +export default class Request extends Body { + constructor(input, init = {}) { + let parsedURL; + + // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245) + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + + if (parsedURL.username !== '' || parsedURL.password !== '') { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + + let method = init.method || input.method || 'GET'; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + + if (!isRequest(init) && 'data' in init) { + doBadDataWarn(); + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if ((init.body != null || (isRequest(input) && input.body !== null)) && + (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + const inputBody = init.body ? + init.body : + (isRequest(input) && input.body !== null ? + clone(input) : + null); + + super(inputBody, { + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? + input.signal : + null; + if ('signal' in init) { + signal = init.signal; + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget'); + } + + // §5.4, Request constructor steps, step 15.1 + // eslint-disable-next-line no-eq-null, eqeqeq + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === '') { + // §5.4, Request constructor steps, step 15.2 + referrer = 'no-referrer'; + } else if (referrer) { + // §5.4, Request constructor steps, step 15.3.1, 15.3.2 + const parsedReferrer = new URL(referrer); + // §5.4, Request constructor steps, step 15.3.3, 15.3.4 + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer; + } else { + referrer = undefined; + } + + this[INTERNALS] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal, + referrer + }; + + // Node-fetch-only options + this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow; + this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + + // §5.4, Request constructor steps, step 16. + // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ''; + } + + /** @returns {string} */ + get method() { + return this[INTERNALS].method; + } + + /** @returns {string} */ + get url() { + return formatUrl(this[INTERNALS].parsedURL); + } + + /** @returns {Headers} */ + get headers() { + return this[INTERNALS].headers; + } + + get redirect() { + return this[INTERNALS].redirect; + } + + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS].signal; + } + + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS].referrer === 'no-referrer') { + return ''; + } + + if (this[INTERNALS].referrer === 'client') { + return 'about:client'; + } + + if (this[INTERNALS].referrer) { + return this[INTERNALS].referrer.toString(); + } + + return undefined; + } + + get referrerPolicy() { + return this[INTERNALS].referrerPolicy; + } + + set referrerPolicy(referrerPolicy) { + this[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + + get [Symbol.toStringTag]() { + return 'Request'; + } +} + +Object.defineProperties(Request.prototype, { + method: {enumerable: true}, + url: {enumerable: true}, + headers: {enumerable: true}, + redirect: {enumerable: true}, + clone: {enumerable: true}, + signal: {enumerable: true}, + referrer: {enumerable: true}, + referrerPolicy: {enumerable: true} +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param {Request} request - A Request instance + * @return The options object to be passed to http.request + */ +export const getNodeRequestOptions = request => { + const {parsedURL} = request[INTERNALS]; + const headers = new Headers(request[INTERNALS].headers); + + // Fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body === null && /^(post|put)$/i.test(request.method)) { + contentLengthValue = '0'; + } + + if (request.body !== null) { + const totalBytes = getTotalBytes(request); + // Set Content-Length if totalBytes is a number (that is not NaN) + if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // 4.1. Main fetch, step 2.6 + // > If request's referrer policy is the empty string, then set request's referrer policy to the + // > default referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + + // 4.1. Main fetch, step 2.7 + // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking + // > determine request's referrer. + if (request.referrer && request.referrer !== 'no-referrer') { + request[INTERNALS].referrer = determineRequestsReferrer(request); + } else { + request[INTERNALS].referrer = 'no-referrer'; + } + + // 4.5. HTTP-network-or-cache fetch, step 6.9 + // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized + // > and isomorphic encoded, to httpRequest's header list. + if (request[INTERNALS].referrer instanceof URL) { + headers.set('Referer', request.referrer); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip, deflate, br'); + } + + let {agent} = request; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + const search = getSearch(parsedURL); + + // Pass the full URL directly to request(), but overwrite the following + // options: + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request.method, + headers: headers[Symbol.for('nodejs.util.inspect.custom')](), + insecureHTTPParser: request.insecureHTTPParser, + agent + }; + + return { + /** @type {URL} */ + parsedURL, + options + }; +}; diff --git a/src/libMPC/node_modules/node-fetch/src/response.js b/src/libMPC/node_modules/node-fetch/src/response.js new file mode 100644 index 0000000..9806c0c --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/response.js @@ -0,0 +1,160 @@ +/** + * Response.js + * + * Response class provides content decoding + */ + +import Headers from './headers.js'; +import Body, {clone, extractContentType} from './body.js'; +import {isRedirect} from './utils/is-redirect.js'; + +const INTERNALS = Symbol('Response internals'); + +/** + * Response class + * + * Ref: https://fetch.spec.whatwg.org/#response-class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +export default class Response extends Body { + constructor(body = null, options = {}) { + super(body, options); + + // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition + const status = options.status != null ? options.status : 200; + + const headers = new Headers(options.headers); + + if (body !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS] = { + type: 'default', + url: options.url, + status, + statusText: options.statusText || '', + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + + get type() { + return this[INTERNALS].type; + } + + get url() { + return this[INTERNALS].url || ''; + } + + get status() { + return this[INTERNALS].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300; + } + + get redirected() { + return this[INTERNALS].counter > 0; + } + + get statusText() { + return this[INTERNALS].statusText; + } + + get headers() { + return this[INTERNALS].headers; + } + + get highWaterMark() { + return this[INTERNALS].highWaterMark; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + + return new Response(null, { + headers: { + location: new URL(url).toString() + }, + status + }); + } + + static error() { + const response = new Response(null, {status: 0, statusText: ''}); + response[INTERNALS].type = 'error'; + return response; + } + + static json(data = undefined, init = {}) { + const body = JSON.stringify(data); + + if (body === undefined) { + throw new TypeError('data is not JSON serializable'); + } + + const headers = new Headers(init && init.headers); + + if (!headers.has('content-type')) { + headers.set('content-type', 'application/json'); + } + + return new Response(body, { + ...init, + headers + }); + } + + get [Symbol.toStringTag]() { + return 'Response'; + } +} + +Object.defineProperties(Response.prototype, { + type: {enumerable: true}, + url: {enumerable: true}, + status: {enumerable: true}, + ok: {enumerable: true}, + redirected: {enumerable: true}, + statusText: {enumerable: true}, + headers: {enumerable: true}, + clone: {enumerable: true} +}); diff --git a/src/libMPC/node_modules/node-fetch/src/utils/get-search.js b/src/libMPC/node_modules/node-fetch/src/utils/get-search.js new file mode 100644 index 0000000..d067e7c --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/utils/get-search.js @@ -0,0 +1,9 @@ +export const getSearch = parsedURL => { + if (parsedURL.search) { + return parsedURL.search; + } + + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : ''); + return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : ''; +}; diff --git a/src/libMPC/node_modules/node-fetch/src/utils/is-redirect.js b/src/libMPC/node_modules/node-fetch/src/utils/is-redirect.js new file mode 100644 index 0000000..d1347f0 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/utils/is-redirect.js @@ -0,0 +1,11 @@ +const redirectStatus = new Set([301, 302, 303, 307, 308]); + +/** + * Redirect code matching + * + * @param {number} code - Status code + * @return {boolean} + */ +export const isRedirect = code => { + return redirectStatus.has(code); +}; diff --git a/src/libMPC/node_modules/node-fetch/src/utils/is.js b/src/libMPC/node_modules/node-fetch/src/utils/is.js new file mode 100644 index 0000000..f9e467e --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/utils/is.js @@ -0,0 +1,87 @@ +/** + * Is.js + * + * Object type checks. + */ + +const NAME = Symbol.toStringTag; + +/** + * Check if `obj` is a URLSearchParams object + * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143 + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isURLSearchParameters = object => { + return ( + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + typeof object.sort === 'function' && + object[NAME] === 'URLSearchParams' + ); +}; + +/** + * Check if `object` is a W3C `Blob` object (which `File` inherits from) + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isBlob = object => { + return ( + object && + typeof object === 'object' && + typeof object.arrayBuffer === 'function' && + typeof object.type === 'string' && + typeof object.stream === 'function' && + typeof object.constructor === 'function' && + /^(Blob|File)$/.test(object[NAME]) + ); +}; + +/** + * Check if `obj` is an instance of AbortSignal. + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isAbortSignal = object => { + return ( + typeof object === 'object' && ( + object[NAME] === 'AbortSignal' || + object[NAME] === 'EventTarget' + ) + ); +}; + +/** + * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of + * the parent domain. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +export const isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + + return orig === dest || orig.endsWith(`.${dest}`); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +export const isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + + return orig === dest; +}; diff --git a/src/libMPC/node_modules/node-fetch/src/utils/multipart-parser.js b/src/libMPC/node_modules/node-fetch/src/utils/multipart-parser.js new file mode 100644 index 0000000..5ad06f9 --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/utils/multipart-parser.js @@ -0,0 +1,432 @@ +import {File} from 'fetch-blob/from.js'; +import {FormData} from 'formdata-polyfill/esm.min.js'; + +let s = 0; +const S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ +}; + +let f = 1; +const F = { + PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 +}; + +const LF = 10; +const CR = 13; +const SPACE = 32; +const HYPHEN = 45; +const COLON = 58; +const A = 97; +const Z = 122; + +const lower = c => c | 0x20; + +const noop = () => {}; + +class MultipartParser { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + + this.boundaryChars = {}; + + boundary = '\r\n--' + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i = 0; i < boundary.length; i++) { + ui8a[i] = boundary.charCodeAt(i); + this.boundaryChars[ui8a[i]] = true; + } + + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + + /** + * @param {Uint8Array} data + */ + write(data) { + let i = 0; + const length_ = data.length; + let previousIndex = this.index; + let {lookbehind, boundary, boundaryChars, index, state, flags} = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + + const mark = name => { + this[name + 'Mark'] = i; + }; + + const clear = name => { + delete this[name + 'Mark']; + }; + + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + + const dataCallback = (name, clear) => { + const markSymbol = name + 'Mark'; + if (!(markSymbol in this)) { + return; + } + + if (clear) { + callback(name, this[markSymbol], i, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + + for (i = 0; i < length_; i++) { + c = data[i]; + + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + } else { + return; + } + + break; + } + + if (c !== boundary[index + 2]) { + index = -2; + } + + if (c === boundary[index + 2]) { + index++; + } + + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('onHeaderField'); + index = 0; + // falls through + case S.HEADER_FIELD: + if (c === CR) { + clear('onHeaderField'); + state = S.HEADERS_ALMOST_DONE; + break; + } + + index++; + if (c === HYPHEN) { + break; + } + + if (c === COLON) { + if (index === 1) { + // empty header field + return; + } + + dataCallback('onHeaderField', true); + state = S.HEADER_VALUE_START; + break; + } + + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + + mark('onHeaderValue'); + state = S.HEADER_VALUE; + // falls through + case S.HEADER_VALUE: + if (c === CR) { + dataCallback('onHeaderValue', true); + callback('onHeaderEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + + callback('onHeadersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('onPartData'); + // falls through + case S.PART_DATA: + previousIndex = index; + + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(data[i] in boundaryChars)) { + i += boundaryLength; + } + + i -= boundaryEnd; + c = data[i]; + } + + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback('onPartData', true); + } + + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('onPartEnd'); + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback('onPartEnd'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + + if (index > 0) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback('onPartData', 0, previousIndex, _lookbehind); + previousIndex = 0; + mark('onPartData'); + + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } + + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + + dataCallback('onHeaderField'); + dataCallback('onHeaderValue'); + dataCallback('onPartData'); + + // Update properties for the next call + this.index = index; + this.state = state; + this.flags = flags; + } + + end() { + if ((this.state === S.HEADER_FIELD_START && this.index === 0) || + (this.state === S.PART_DATA && this.index === this.boundary.length)) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error('MultipartParser.end(): stream ended unexpectedly'); + } + } +} + +function _fileName(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m) { + return; + } + + const match = m[2] || m[3] || ''; + let filename = match.slice(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m, code) => { + return String.fromCharCode(code); + }); + return filename; +} + +export async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError('Failed to fetch'); + } + + const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + if (!m) { + throw new TypeError('no or bad content-type header, no multipart boundary'); + } + + const parser = new MultipartParser(m[1] || m[2]); + + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + + const onPartData = ui8a => { + entryValue += decoder.decode(ui8a, {stream: true}); + }; + + const appendToFile = ui8a => { + entryChunks.push(ui8a); + }; + + const appendFileToFormData = () => { + const file = new File(entryChunks, filename, {type: contentType}); + formData.append(entryName, file); + }; + + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + + const decoder = new TextDecoder('utf-8'); + decoder.decode(); + + parser.onPartBegin = function () { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + + headerField = ''; + headerValue = ''; + entryValue = ''; + entryName = ''; + contentType = ''; + filename = null; + entryChunks.length = 0; + }; + + parser.onHeaderField = function (ui8a) { + headerField += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderValue = function (ui8a) { + headerValue += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderEnd = function () { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + + if (headerField === 'content-disposition') { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + + if (m) { + entryName = m[2] || m[3] || ''; + } + + filename = _fileName(headerValue); + + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === 'content-type') { + contentType = headerValue; + } + + headerValue = ''; + headerField = ''; + }; + + for await (const chunk of Body) { + parser.write(chunk); + } + + parser.end(); + + return formData; +} diff --git a/src/libMPC/node_modules/node-fetch/src/utils/referrer.js b/src/libMPC/node_modules/node-fetch/src/utils/referrer.js new file mode 100644 index 0000000..6741f2f --- /dev/null +++ b/src/libMPC/node_modules/node-fetch/src/utils/referrer.js @@ -0,0 +1,340 @@ +import {isIP} from 'node:net'; + +/** + * @external URL + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL} + */ + +/** + * @module utils/referrer + * @private + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer} + * @param {string} URL + * @param {boolean} [originOnly=false] + */ +export function stripURLForUseAsAReferrer(url, originOnly = false) { + // 1. If url is null, return no referrer. + if (url == null) { // eslint-disable-line no-eq-null, eqeqeq + return 'no-referrer'; + } + + url = new URL(url); + + // 2. If url's scheme is a local scheme, then return no referrer. + if (/^(about|blob|data):$/.test(url.protocol)) { + return 'no-referrer'; + } + + // 3. Set url's username to the empty string. + url.username = ''; + + // 4. Set url's password to null. + // Note: `null` appears to be a mistake as this actually results in the password being `"null"`. + url.password = ''; + + // 5. Set url's fragment to null. + // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`. + url.hash = ''; + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 6.1. Set url's path to null. + // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`. + url.pathname = ''; + + // 6.2. Set url's query to null. + // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`. + url.search = ''; + } + + // 7. Return url. + return url; +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy} + */ +export const ReferrerPolicy = new Set([ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]); + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy} + */ +export const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'; + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies} + * @param {string} referrerPolicy + * @returns {string} referrerPolicy + */ +export function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + + return referrerPolicy; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +export function isOriginPotentiallyTrustworthy(url) { + // 1. If origin is an opaque origin, return "Not Trustworthy". + // Not applicable + + // 2. Assert: origin is a tuple origin. + // Not for implementations + + // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy". + if (/^(http|ws)s:$/.test(url.protocol)) { + return true; + } + + // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy". + const hostIp = url.host.replace(/(^\[)|(]$)/g, ''); + const hostIPVersion = isIP(hostIp); + + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + + // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy". + // We are returning FALSE here because we cannot ensure conformance to + // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost) + if (url.host === 'localhost' || url.host.endsWith('.localhost')) { + return false; + } + + // 6. If origin's scheme component is file, return "Potentially Trustworthy". + if (url.protocol === 'file:') { + return true; + } + + // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy". + // Not supported + + // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy". + // Not supported + + // 9. Return "Not Trustworthy". + return false; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +export function isUrlPotentiallyTrustworthy(url) { + // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy". + if (/^about:(blank|srcdoc)$/.test(url)) { + return true; + } + + // 2. If url's scheme is "data", return "Potentially Trustworthy". + if (url.protocol === 'data:') { + return true; + } + + // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were + // created. Therefore, blobs created in a trustworthy origin will themselves be potentially + // trustworthy. + if (/^(blob|filesystem):$/.test(url.protocol)) { + return true; + } + + // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin. + return isOriginPotentiallyTrustworthy(url); +} + +/** + * Modifies the referrerURL to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerURLCallback + * @param {external:URL} referrerURL + * @returns {external:URL} modified referrerURL + */ + +/** + * Modifies the referrerOrigin to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerOriginCallback + * @param {external:URL} referrerOrigin + * @returns {external:URL} modified referrerOrigin + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer} + * @param {Request} request + * @param {object} o + * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback + * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback + * @returns {external:URL} Request's referrer + */ +export function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) { + // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for + // these cases: + // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm. + // > Note: If request's referrer policy is the empty string, Fetch will not call into this + // > algorithm. + if (request.referrer === 'no-referrer' || request.referrerPolicy === '') { + return null; + } + + // 1. Let policy be request's associated referrer policy. + const policy = request.referrerPolicy; + + // 2. Let environment be request's client. + // not applicable to node.js + + // 3. Switch on request's referrer: + if (request.referrer === 'about:client') { + return 'no-referrer'; + } + + // "a URL": Let referrerSource be request's referrer. + const referrerSource = request.referrer; + + // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer. + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the + // origin-only flag set to true. + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + + // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set + // referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary + // policy considerations in the interests of minimizing data leakage. For example, the user + // agent could strip the URL down to an origin, modify its host, replace it with an empty + // string, etc. + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + + // 8.Execute the statements corresponding to the value of policy: + const currentURL = new URL(request.url); + + switch (policy) { + case 'no-referrer': + return 'no-referrer'; + + case 'origin': + return referrerOrigin; + + case 'unsafe-url': + return referrerURL; + + case 'strict-origin': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerOrigin. + return referrerOrigin.toString(); + + case 'strict-origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 3. Return referrerOrigin. + return referrerOrigin; + + case 'same-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. Return no referrer. + return 'no-referrer'; + + case 'origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // Return referrerOrigin. + return referrerOrigin; + + case 'no-referrer-when-downgrade': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerURL. + return referrerURL; + + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header} + * @param {Headers} headers Response headers + * @returns {string} policy + */ +export function parseReferrerPolicyFromHeader(headers) { + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` + // and response’s header list. + const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/); + + // 2. Let policy be the empty string. + let policy = ''; + + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty + // string, then set policy to token. + // Note: This algorithm loops over multiple policy values to allow deployment of new policy + // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values. + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + + // 4. Return policy. + return policy; +} diff --git a/src/libMPC/node_modules/randombytes/.travis.yml b/src/libMPC/node_modules/randombytes/.travis.yml new file mode 100644 index 0000000..69fdf71 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '7' + env: TEST_SUITE=test + - node_js: '6' + env: TEST_SUITE=test + - node_js: '5' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=phantom +script: "npm run-script $TEST_SUITE" diff --git a/src/libMPC/node_modules/randombytes/.zuul.yml b/src/libMPC/node_modules/randombytes/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/src/libMPC/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/src/libMPC/node_modules/randombytes/LICENSE b/src/libMPC/node_modules/randombytes/LICENSE new file mode 100644 index 0000000..fea9d48 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 crypto-browserify + +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. diff --git a/src/libMPC/node_modules/randombytes/README.md b/src/libMPC/node_modules/randombytes/README.md new file mode 100644 index 0000000..3bacba4 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/README.md @@ -0,0 +1,14 @@ +randombytes +=== + +[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) + +randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues + +```js +var randomBytes = require('randombytes'); +randomBytes(16);//get 16 random bytes +randomBytes(16, function (err, resp) { + // resp is 16 random bytes +}); +``` diff --git a/src/libMPC/node_modules/randombytes/browser.js b/src/libMPC/node_modules/randombytes/browser.js new file mode 100644 index 0000000..0fb0b71 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/browser.js @@ -0,0 +1,50 @@ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} diff --git a/src/libMPC/node_modules/randombytes/index.js b/src/libMPC/node_modules/randombytes/index.js new file mode 100644 index 0000000..a2d9e39 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/src/libMPC/node_modules/randombytes/package.json b/src/libMPC/node_modules/randombytes/package.json new file mode 100644 index 0000000..3623652 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/package.json @@ -0,0 +1,36 @@ +{ + "name": "randombytes", + "version": "2.1.0", + "description": "random bytes from browserify stand alone", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec", + "phantom": "zuul --phantom -- test.js", + "local": "zuul --local --no-coverage -- test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:crypto-browserify/randombytes.git" + }, + "keywords": [ + "crypto", + "random" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/randombytes/issues" + }, + "homepage": "https://github.com/crypto-browserify/randombytes", + "browser": "browser.js", + "devDependencies": { + "phantomjs": "^1.9.9", + "standard": "^10.0.2", + "tap-spec": "^2.1.2", + "tape": "^4.6.3", + "zuul": "^3.7.2" + }, + "dependencies": { + "safe-buffer": "^5.1.0" + } +} diff --git a/src/libMPC/node_modules/randombytes/test.js b/src/libMPC/node_modules/randombytes/test.js new file mode 100644 index 0000000..f266976 --- /dev/null +++ b/src/libMPC/node_modules/randombytes/test.js @@ -0,0 +1,81 @@ +var test = require('tape') +var randomBytes = require('./') +var MAX_BYTES = 65536 +var MAX_UINT32 = 4294967295 + +test('sync', function (t) { + t.plan(9) + t.equals(randomBytes(0).length, 0, 'len: ' + 0) + t.equals(randomBytes(3).length, 3, 'len: ' + 3) + t.equals(randomBytes(30).length, 30, 'len: ' + 30) + t.equals(randomBytes(300).length, 300, 'len: ' + 300) + t.equals(randomBytes(17 + MAX_BYTES).length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + t.equals(randomBytes(MAX_BYTES * 100).length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + t.throws(function () { + randomBytes(MAX_UINT32 + 1) + }) + t.throws(function () { + t.equals(randomBytes(-1)) + }) + t.throws(function () { + t.equals(randomBytes('hello')) + }) +}) + +test('async', function (t) { + t.plan(9) + + randomBytes(0, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 0, 'len: ' + 0) + }) + + randomBytes(3, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 3, 'len: ' + 3) + }) + + randomBytes(30, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 30, 'len: ' + 30) + }) + + randomBytes(300, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 300, 'len: ' + 300) + }) + + randomBytes(17 + MAX_BYTES, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + }) + + randomBytes(MAX_BYTES * 100, function (err, resp) { + if (err) throw err + + t.equals(resp.length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + }) + + t.throws(function () { + randomBytes(MAX_UINT32 + 1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes(-1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes('hello', function () { + t.ok(false, 'should not get here') + }) + }) +}) diff --git a/src/libMPC/node_modules/readable-stream/CONTRIBUTING.md b/src/libMPC/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/src/libMPC/node_modules/readable-stream/GOVERNANCE.md b/src/libMPC/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/src/libMPC/node_modules/readable-stream/LICENSE b/src/libMPC/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" diff --git a/src/libMPC/node_modules/readable-stream/README.md b/src/libMPC/node_modules/readable-stream/README.md new file mode 100644 index 0000000..19117c1 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/src/libMPC/node_modules/readable-stream/errors-browser.js b/src/libMPC/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..fb8e73e --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/src/libMPC/node_modules/readable-stream/errors.js b/src/libMPC/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/src/libMPC/node_modules/readable-stream/experimentalWarning.js b/src/libMPC/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/src/libMPC/node_modules/readable-stream/lib/_stream_duplex.js b/src/libMPC/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..19abfa6 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// 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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/_stream_passthrough.js b/src/libMPC/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..24a6bdd --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// 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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/_stream_readable.js b/src/libMPC/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..df1f608 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// 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. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/_stream_transform.js b/src/libMPC/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..1ccb715 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// 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. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/_stream_writable.js b/src/libMPC/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..292415e --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..742c5a4 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..69bda49 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/destroy.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..31a17c4 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..59c671b --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/from-browser.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000..a4ce56f --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/from.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000..0a34ee9 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/pipeline.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..e6f3924 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/state.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..3fbf892 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream.js b/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/src/libMPC/node_modules/readable-stream/package.json b/src/libMPC/node_modules/readable-stream/package.json new file mode 100644 index 0000000..ade59e7 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/src/libMPC/node_modules/readable-stream/readable-browser.js b/src/libMPC/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..adbf60d --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/src/libMPC/node_modules/readable-stream/readable.js b/src/libMPC/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..9e0ca12 --- /dev/null +++ b/src/libMPC/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/src/libMPC/node_modules/ripemd160/CHANGELOG.md b/src/libMPC/node_modules/ripemd160/CHANGELOG.md new file mode 100644 index 0000000..91ba912 --- /dev/null +++ b/src/libMPC/node_modules/ripemd160/CHANGELOG.md @@ -0,0 +1,72 @@ +2.0.1 / 2016-06-22 +------------------ +- added LICENSE file. + +2.0.0 / 2016-04-11 +------------------ +- rewritten, license change BSD-3 to MIT. [#13][#13] +- stream support [#13][#13] + +1.0.1 / 2015-05-05 +------------------ +- standard formatting + +1.0.0 / 2015-01-14 +------------------ +- updated dev deps +- added more test fixtures +- updated readme with usage, testing, etc +- moved from https://github.com/cryptocoinjs/ripemd160 to https://github.com/crypto-browserify/ripemd160 + +0.2.1 / 2014-12-31 +------------------ +- made license clear in `package.json` +- deleted `Makefile`, moved targets to `package.json` +- removed `terst` for `assert` + +0.2.0 / 2014-03-09 +------------------ +* removed bower.json and component.json +* changed 4 spacing to 2 +* returns `Buffer` type now, input must be Array, Uint8Array, Buffer, or string +* remove deps: `convert-hex` and `convert-string` + +0.1.0 / 2013-11-20 +------------------ +* changed package name +* removed AMD support + +0.0.2 / 2013-11-06 +------------------ +* fixed component.json file + +0.0.1 / 2013-11-03 +------------------ +* initial release + + +[#13]: https://github.com/crypto-browserify/ripemd160/pull/13 + +[#12]: https://github.com/crypto-browserify/ripemd160/pull/12 + +[#11]: https://github.com/crypto-browserify/ripemd160/pull/11 + +[#10]: https://github.com/crypto-browserify/ripemd160/pull/10 + +[#9]: https://github.com/crypto-browserify/ripemd160/pull/9 + +[#8]: https://github.com/crypto-browserify/ripemd160/issues/8 + +[#7]: https://github.com/crypto-browserify/ripemd160/pull/7 + +[#6]: https://github.com/crypto-browserify/ripemd160/pull/6 + +[#5]: https://github.com/crypto-browserify/ripemd160/issues/5 + +[#4]: https://github.com/crypto-browserify/ripemd160/pull/4 + +[#3]: https://github.com/crypto-browserify/ripemd160/pull/3 + +[#2]: https://github.com/crypto-browserify/ripemd160/pull/2 + +[#1]: https://github.com/crypto-browserify/ripemd160/pull/1 diff --git a/src/libMPC/node_modules/ripemd160/LICENSE b/src/libMPC/node_modules/ripemd160/LICENSE new file mode 100644 index 0000000..cbe3544 --- /dev/null +++ b/src/libMPC/node_modules/ripemd160/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 crypto-browserify + +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. diff --git a/src/libMPC/node_modules/ripemd160/README.md b/src/libMPC/node_modules/ripemd160/README.md new file mode 100644 index 0000000..056c6a2 --- /dev/null +++ b/src/libMPC/node_modules/ripemd160/README.md @@ -0,0 +1,27 @@ +# ripemd160 + +[![NPM Package](https://img.shields.io/npm/v/ripemd160.svg?style=flat-square)](https://www.npmjs.org/package/ripemd160) +[![Build Status](https://img.shields.io/travis/crypto-browserify/ripemd160.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/ripemd160) +[![Dependency status](https://img.shields.io/david/crypto-browserify/ripemd160.svg?style=flat-square)](https://david-dm.org/crypto-browserify/ripemd160#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Node style `ripemd160` on pure JavaScript. + +## Example + +```js +var RIPEMD160 = require('ripemd160') + +console.log(new RIPEMD160().update('42').digest('hex')) +// => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 + +var ripemd160stream = new RIPEMD160() +ripemd160stream.end('42') +console.log(ripemd160stream.read().toString('hex')) +// => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 +``` + +## LICENSE + +MIT diff --git a/src/libMPC/node_modules/ripemd160/index.js b/src/libMPC/node_modules/ripemd160/index.js new file mode 100644 index 0000000..870de9c --- /dev/null +++ b/src/libMPC/node_modules/ripemd160/index.js @@ -0,0 +1,163 @@ +'use strict' +var Buffer = require('buffer').Buffer +var inherits = require('inherits') +var HashBase = require('hash-base') + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} + +module.exports = RIPEMD160 diff --git a/src/libMPC/node_modules/ripemd160/package.json b/src/libMPC/node_modules/ripemd160/package.json new file mode 100644 index 0000000..70d3c60 --- /dev/null +++ b/src/libMPC/node_modules/ripemd160/package.json @@ -0,0 +1,37 @@ +{ + "name": "ripemd160", + "version": "2.0.2", + "description": "Compute ripemd160 of bytes or strings.", + "keywords": [ + "string", + "strings", + "ripemd160", + "ripe160", + "bitcoin", + "bytes", + "cryptography" + ], + "license": "MIT", + "files": [ + "index.js" + ], + "main": "./index", + "repository": { + "url": "https://github.com/crypto-browserify/ripemd160", + "type": "git" + }, + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "node test/*.js" + }, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + }, + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "standard": "^6.0.7", + "tape": "^4.5.1" + } +} diff --git a/src/libMPC/node_modules/safe-buffer/LICENSE b/src/libMPC/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/src/libMPC/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/src/libMPC/node_modules/safe-buffer/README.md b/src/libMPC/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/src/libMPC/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/src/libMPC/node_modules/safe-buffer/index.d.ts b/src/libMPC/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/src/libMPC/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/src/libMPC/node_modules/safe-buffer/index.js b/src/libMPC/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/src/libMPC/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/src/libMPC/node_modules/safe-buffer/package.json b/src/libMPC/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/src/libMPC/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/src/libMPC/node_modules/sha.js/.travis.yml b/src/libMPC/node_modules/sha.js/.travis.yml new file mode 100644 index 0000000..0b606eb --- /dev/null +++ b/src/libMPC/node_modules/sha.js/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +os: + - linux +language: node_js +node_js: + - "4" + - "5" + - "6" + - "7" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "7" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/src/libMPC/node_modules/sha.js/LICENSE b/src/libMPC/node_modules/sha.js/LICENSE new file mode 100644 index 0000000..11888c1 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/LICENSE @@ -0,0 +1,49 @@ +Copyright (c) 2013-2018 sha.js 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. + + +Copyright (c) 1998 - 2009, Paul Johnston & Contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +Neither the name of the author nor the names of its contributors may be used to +endorse or promote products derived from this software without specific prior +written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/libMPC/node_modules/sha.js/README.md b/src/libMPC/node_modules/sha.js/README.md new file mode 100644 index 0000000..1cc3db5 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/README.md @@ -0,0 +1,44 @@ +# sha.js +[![NPM Package](https://img.shields.io/npm/v/sha.js.svg?style=flat-square)](https://www.npmjs.org/package/sha.js) +[![Build Status](https://img.shields.io/travis/crypto-browserify/sha.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/sha.js) +[![Dependency status](https://img.shields.io/david/crypto-browserify/sha.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/sha.js#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Node style `SHA` on pure JavaScript. + +```js +var shajs = require('sha.js') + +console.log(shajs('sha256').update('42').digest('hex')) +// => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 +console.log(new shajs.sha256().update('42').digest('hex')) +// => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 + +var sha256stream = shajs('sha256') +sha256stream.end('42') +console.log(sha256stream.read().toString('hex')) +// => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 +``` + +## supported hashes +`sha.js` currently implements: + + - SHA (SHA-0) -- **legacy, do not use in new systems** + - SHA-1 -- **legacy, do not use in new systems** + - SHA-224 + - SHA-256 + - SHA-384 + - SHA-512 + + +## Not an actual stream +Note, this doesn't actually implement a stream, but wrapping this in a stream is trivial. +It does update incrementally, so you can hash things larger than RAM, as it uses a constant amount of memory (except when using base64 or utf8 encoding, see code comments). + + +## Acknowledgements +This work is derived from Paul Johnston's [A JavaScript implementation of the Secure Hash Algorithm](http://pajhome.org.uk/crypt/md5/sha1.html). + + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/sha.js/bin.js b/src/libMPC/node_modules/sha.js/bin.js new file mode 100755 index 0000000..5a7ac83 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/bin.js @@ -0,0 +1,41 @@ +#! /usr/bin/env node + +var createHash = require('./browserify') +var argv = process.argv.slice(2) + +function pipe (algorithm, s) { + var start = Date.now() + var hash = createHash(algorithm || 'sha1') + + s.on('data', function (data) { + hash.update(data) + }) + + s.on('end', function () { + if (process.env.DEBUG) { + return console.log(hash.digest('hex'), Date.now() - start) + } + + console.log(hash.digest('hex')) + }) +} + +function usage () { + console.error('sha.js [algorithm=sha1] [filename] # hash filename with algorithm') + console.error('input | sha.js [algorithm=sha1] # hash stdin with algorithm') + console.error('sha.js --help # display this message') +} + +if (!process.stdin.isTTY) { + pipe(argv[0], process.stdin) +} else if (argv.length) { + if (/--help|-h/.test(argv[0])) { + usage() + } else { + var filename = argv.pop() + var algorithm = argv.pop() + pipe(algorithm, require('fs').createReadStream(filename)) + } +} else { + usage() +} diff --git a/src/libMPC/node_modules/sha.js/hash.js b/src/libMPC/node_modules/sha.js/hash.js new file mode 100644 index 0000000..013537a --- /dev/null +++ b/src/libMPC/node_modules/sha.js/hash.js @@ -0,0 +1,81 @@ +var Buffer = require('safe-buffer').Buffer + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash diff --git a/src/libMPC/node_modules/sha.js/index.js b/src/libMPC/node_modules/sha.js/index.js new file mode 100644 index 0000000..87cdf49 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/index.js @@ -0,0 +1,15 @@ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') diff --git a/src/libMPC/node_modules/sha.js/package.json b/src/libMPC/node_modules/sha.js/package.json new file mode 100644 index 0000000..bfe633b --- /dev/null +++ b/src/libMPC/node_modules/sha.js/package.json @@ -0,0 +1,30 @@ +{ + "name": "sha.js", + "description": "Streamable SHA hashes in pure javascript", + "version": "2.4.11", + "homepage": "https://github.com/crypto-browserify/sha.js", + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/sha.js.git" + }, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "buffer": "~2.3.2", + "hash-test-vectors": "^1.3.1", + "standard": "^10.0.2", + "tape": "~2.3.2", + "typedarray": "0.0.6" + }, + "bin": "./bin.js", + "scripts": { + "prepublish": "npm ls && npm run unit", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "set -e; for t in test/*.js; do node $t; done;" + }, + "author": "Dominic Tarr (dominictarr.com)", + "license": "(MIT AND BSD-3-Clause)" +} diff --git a/src/libMPC/node_modules/sha.js/sha.js b/src/libMPC/node_modules/sha.js/sha.js new file mode 100644 index 0000000..50c4fa8 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha.js @@ -0,0 +1,94 @@ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha diff --git a/src/libMPC/node_modules/sha.js/sha1.js b/src/libMPC/node_modules/sha.js/sha1.js new file mode 100644 index 0000000..cabd747 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha1.js @@ -0,0 +1,99 @@ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 diff --git a/src/libMPC/node_modules/sha.js/sha224.js b/src/libMPC/node_modules/sha.js/sha224.js new file mode 100644 index 0000000..35541e5 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha224.js @@ -0,0 +1,53 @@ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 diff --git a/src/libMPC/node_modules/sha.js/sha256.js b/src/libMPC/node_modules/sha.js/sha256.js new file mode 100644 index 0000000..342e48a --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha256.js @@ -0,0 +1,135 @@ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 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 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + 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 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 diff --git a/src/libMPC/node_modules/sha.js/sha384.js b/src/libMPC/node_modules/sha.js/sha384.js new file mode 100644 index 0000000..afc85e5 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha384.js @@ -0,0 +1,57 @@ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 diff --git a/src/libMPC/node_modules/sha.js/sha512.js b/src/libMPC/node_modules/sha.js/sha512.js new file mode 100644 index 0000000..fb28f2f --- /dev/null +++ b/src/libMPC/node_modules/sha.js/sha512.js @@ -0,0 +1,260 @@ +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 diff --git a/src/libMPC/node_modules/sha.js/test/hash.js b/src/libMPC/node_modules/sha.js/test/hash.js new file mode 100644 index 0000000..5fa000d --- /dev/null +++ b/src/libMPC/node_modules/sha.js/test/hash.js @@ -0,0 +1,75 @@ +var tape = require('tape') +var Hash = require('../hash') +var hex = '0A1B2C3D4E5F6G7H' + +function equal (t, a, b) { + t.equal(a.length, b.length) + t.equal(a.toString('hex'), b.toString('hex')) +} + +var hexBuf = Buffer.from('0A1B2C3D4E5F6G7H', 'utf8') +var count16 = { + strings: ['0A1B2C3D4E5F6G7H'], + buffers: [ + hexBuf, + Buffer.from('80000000000000000000000000000080', 'hex') + ] +} + +var empty = { + strings: [''], + buffers: [ + Buffer.from('80000000000000000000000000000000', 'hex') + ] +} + +var multi = { + strings: ['abcd', 'efhijk', 'lmnopq'], + buffers: [ + Buffer.from('abcdefhijklmnopq', 'ascii'), + Buffer.from('80000000000000000000000000000080', 'hex') + ] +} + +var long = { + strings: [hex + hex], + buffers: [ + hexBuf, + hexBuf, + Buffer.from('80000000000000000000000000000100', 'hex') + ] +} + +function makeTest (name, data) { + tape(name, function (t) { + var h = new Hash(16, 8) + var hash = Buffer.alloc(20) + var n = 2 + var expected = data.buffers.slice() + // t.plan(expected.length + 1) + + h._update = function (block) { + var e = expected.shift() + equal(t, block, e) + + if (n < 0) { + throw new Error('expecting only 2 calls to _update') + } + } + h._hash = function () { + return hash + } + + data.strings.forEach(function (string) { + h.update(string, 'ascii') + }) + + equal(t, h.digest(), hash) + t.end() + }) +} + +makeTest('Hash#update 1 in 1', count16) +makeTest('empty Hash#update', empty) +makeTest('Hash#update 1 in 3', multi) +makeTest('Hash#update 2 in 1', long) diff --git a/src/libMPC/node_modules/sha.js/test/test.js b/src/libMPC/node_modules/sha.js/test/test.js new file mode 100644 index 0000000..dac8580 --- /dev/null +++ b/src/libMPC/node_modules/sha.js/test/test.js @@ -0,0 +1,100 @@ +var crypto = require('crypto') +var tape = require('tape') +var Sha1 = require('../').sha1 + +var inputs = [ + ['', 'ascii'], + ['abc', 'ascii'], + ['123', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789abcdef', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789abc', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789ab', 'ascii'], + ['0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde', 'ascii'], + ['0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', 'ascii'], + ['foobarbaz', 'ascii'] +] + +tape("hash is the same as node's crypto", function (t) { + inputs.forEach(function (v) { + var a = new Sha1().update(v[0], v[1]).digest('hex') + var e = crypto.createHash('sha1').update(v[0], v[1]).digest('hex') + console.log(a, '==', e) + t.equal(a, e) + }) + + t.end() +}) + +tape('call update multiple times', function (t) { + inputs.forEach(function (v) { + var hash = new Sha1() + var _hash = crypto.createHash('sha1') + + for (var i = 0; i < v[0].length; i = (i + 1) * 2) { + var s = v[0].substring(i, (i + 1) * 2) + hash.update(s, v[1]) + _hash.update(s, v[1]) + } + + var a = hash.digest('hex') + var e = _hash.digest('hex') + console.log(a, '==', e) + t.equal(a, e) + }) + t.end() +}) + +tape('call update twice', function (t) { + var _hash = crypto.createHash('sha1') + var hash = new Sha1() + + _hash.update('foo', 'ascii') + hash.update('foo', 'ascii') + + _hash.update('bar', 'ascii') + hash.update('bar', 'ascii') + + _hash.update('baz', 'ascii') + hash.update('baz', 'ascii') + + var a = hash.digest('hex') + var e = _hash.digest('hex') + + t.equal(a, e) + t.end() +}) + +tape('hex encoding', function (t) { + inputs.forEach(function (v) { + var hash = new Sha1() + var _hash = crypto.createHash('sha1') + + for (var i = 0; i < v[0].length; i = (i + 1) * 2) { + var s = v[0].substring(i, (i + 1) * 2) + hash.update(Buffer.from(s, 'ascii').toString('hex'), 'hex') + _hash.update(Buffer.from(s, 'ascii').toString('hex'), 'hex') + } + var a = hash.digest('hex') + var e = _hash.digest('hex') + + console.log(a, '==', e) + t.equal(a, e) + }) + + t.end() +}) + +tape('call digest for more than MAX_UINT32 bits of data', function (t) { + var _hash = crypto.createHash('sha1') + var hash = new Sha1() + var bigData = Buffer.alloc(0x1ffffffff / 8) + + hash.update(bigData) + _hash.update(bigData) + + var a = hash.digest('hex') + var e = _hash.digest('hex') + + t.equal(a, e) + t.end() +}) diff --git a/src/libMPC/node_modules/sha.js/test/vectors.js b/src/libMPC/node_modules/sha.js/test/vectors.js new file mode 100644 index 0000000..48a646e --- /dev/null +++ b/src/libMPC/node_modules/sha.js/test/vectors.js @@ -0,0 +1,72 @@ +var tape = require('tape') +var vectors = require('hash-test-vectors') +// var from = require('bops/typedarray/from') +var Buffer = require('safe-buffer').Buffer + +var createHash = require('../') + +function makeTest (alg, i, verbose) { + var v = vectors[i] + + tape(alg + ': NIST vector ' + i, function (t) { + if (verbose) { + console.log(v) + console.log('VECTOR', i) + console.log('INPUT', v.input) + console.log(Buffer.from(v.input, 'base64').toString('hex')) + } + + var buf = Buffer.from(v.input, 'base64') + t.equal(createHash(alg).update(buf).digest('hex'), v[alg]) + + i = ~~(buf.length / 2) + var buf1 = buf.slice(0, i) + var buf2 = buf.slice(i, buf.length) + + console.log(buf1.length, buf2.length, buf.length) + console.log(createHash(alg)._block.length) + + t.equal( + createHash(alg) + .update(buf1) + .update(buf2) + .digest('hex'), + v[alg] + ) + + var j, buf3 + + i = ~~(buf.length / 3) + j = ~~(buf.length * 2 / 3) + buf1 = buf.slice(0, i) + buf2 = buf.slice(i, j) + buf3 = buf.slice(j, buf.length) + + t.equal( + createHash(alg) + .update(buf1) + .update(buf2) + .update(buf3) + .digest('hex'), + v[alg] + ) + + setTimeout(function () { + // avoid "too much recursion" errors in tape in firefox + t.end() + }) + }) +} + +if (process.argv[2]) { + makeTest(process.argv[2], parseInt(process.argv[3], 10), true) +} else { + vectors.forEach(function (v, i) { + makeTest('sha', i) + makeTest('sha1', i) + makeTest('sha224', i) + makeTest('sha256', i) + makeTest('sha384', i) + makeTest('sha512', i) + }) +} diff --git a/src/libMPC/node_modules/string_decoder/LICENSE b/src/libMPC/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/src/libMPC/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" + diff --git a/src/libMPC/node_modules/string_decoder/README.md b/src/libMPC/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/src/libMPC/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/src/libMPC/node_modules/string_decoder/lib/string_decoder.js b/src/libMPC/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/src/libMPC/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/src/libMPC/node_modules/string_decoder/package.json b/src/libMPC/node_modules/string_decoder/package.json new file mode 100644 index 0000000..b2bb141 --- /dev/null +++ b/src/libMPC/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/LICENSE b/src/libMPC/node_modules/tiny-secp256k1/LICENSE new file mode 100644 index 0000000..dfc0087 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 bitcoinjs 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. diff --git a/src/libMPC/node_modules/tiny-secp256k1/README.md b/src/libMPC/node_modules/tiny-secp256k1/README.md new file mode 100644 index 0000000..16e8489 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/README.md @@ -0,0 +1,355 @@ +# tiny-secp256k1 + +[![NPM](https://img.shields.io/npm/v/tiny-secp256k1.svg)](https://www.npmjs.org/package/tiny-secp256k1) + +This library is under development, and, like the [secp256k1](https://github.com/bitcoin-core/secp256k1) C library (through [secp256k1-sys](https://github.com/rust-bitcoin/rust-secp256k1/) Rust crate) it depends on, this is a research effort to determine an optimal API for end-users of the bitcoinjs ecosystem. + +## Installation + +### npm + +```bash +npm install tiny-secp256k1 +``` + +### yarn + +```bash +yarn add tiny-secp256k1 +``` + +## WebAssembly and Node.js version + +Previous version of `tiny-secp256k1` implement [C++ addon](https://nodejs.org/api/addons.html) through [NAN (Native Abstractions for Node.js)](https://github.com/nodejs/nan) and [elliptic](https://github.com/indutny/elliptic) as fallback when addon can not be built or in browser-like environement. + +Current version use Rust crate (which use C library) compiled to [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly). With Wasm same code executed in any environment. Wasm is faster than `elliptic` but slower than node bindings ([results in PR](https://github.com/bitcoinjs/tiny-secp256k1/pull/53#issuecomment-801844450) or you can run own benchmark in `benches` directory). + +## Building + +For building locally you need C/C++ toolchain, Rust version >=1.50.0 and `wasm-opt` from [binaryen](https://github.com/WebAssembly/binaryen). + +[rustup](https://rustup.rs/) is a recommended way to install `Rust`. You also will need `wasm32-unknown-unknown` target. + +``` +rustup toolchain install stable --target wasm32-unknown-unknown --component clippy --component rustfmt +``` + +After installing development dependencies with `npm` you can build Wasm: + +``` +make build-wasm +``` + +or run tests: + +``` +make test +``` + +Alternative way is to use [Docker](https://www.docker.com/): + +``` +% docker build -t tiny-secp256k1 . +% docker run -it --rm -v `pwd`:/tiny-secp256k1 -w /tiny-secp256k1 tiny-secp256k1 +# make build +``` + +## Examples + +`tiny-secp256k1` includes two examples. First is [simple script for Node.js](examples/random-in-node) which generate random data and print arguments and methods results. Second is [React app](examples/react-app). + +React app is builded in GitHub Actions on each commit to master branch and uploaded to [gh-pages](https://github.com/bitcoinjs/tiny-secp256k1/tree/gh-pages) branch, which is always available online: https://bitcoinjs.github.io/tiny-secp256k1/ + +## Documentation + +### isPoint (A) + +```haskell +isPoint :: Buffer -> Bool +``` + +Returns `false` if + +- `A` is not encoded with a sequence tag of `0x02`, `0x03` or `0x04` +- `A.x` is not in `[1...p - 1]` +- `A.y` is not in `[1...p - 1]` + +### isPointCompressed (A) + +```haskell +isPointCompressed :: Buffer -> Bool +``` + +Returns `false` if the pubkey is **not** compressed. + +### isXOnlyPoint (A) + +```haskell +isXOnlyPoint :: Buffer -> Bool +``` + +Returns `false` if the pubkey is **not** an xOnlyPubkey. + +### isPrivate (d) + +```haskell +isPrivate :: Buffer -> Bool +``` + +Returns `false` if + +- `d` is not 256-bit, or +- `d` is not in `[1..order - 1]` + +### pointAdd (A, B[, compressed]) + +```haskell +pointAdd :: Buffer -> Buffer [-> Bool] -> Maybe Buffer +``` + +Returns `null` if result is at infinity. + +##### Throws: + +- `Expected Point` if `!isPoint(A)` +- `Expected Point` if `!isPoint(B)` + +### pointAddScalar (A, tweak[, compressed]) + +```haskell +pointAddScalar :: Buffer -> Buffer [-> Bool] -> Maybe Buffer +``` + +Returns `null` if result is at infinity. + +##### Throws: + +- `Expected Point` if `!isPoint(A)` +- `Expected Tweak` if `tweak` is not in `[0...order - 1]` + +### pointCompress (A, compressed) + +```haskell +pointCompress :: Buffer -> Bool -> Buffer +``` + +##### Throws: + +- `Expected Point` if `!isPoint(A)` + +### pointFromScalar (d[, compressed]) + +```haskell +pointFromScalar :: Buffer [-> Bool] -> Maybe Buffer +``` + +Returns `null` if result is at infinity. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` + +### xOnlyPointFromScalar (d) + +```haskell +xOnlyPointFromScalar :: Buffer -> Buffer +``` + +Returns the xOnlyPubkey for a given private key + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` + +### xOnlyPointFromPoint (p) + +```haskell +xOnlyPointFromPoint :: Buffer -> Buffer +``` + +Returns the xOnlyPubkey for a given DER public key + +##### Throws: + +- `Expected Point` if `!isPoint(p)` + +### pointMultiply (A, tweak[, compressed]) + +```haskell +pointMultiply :: Buffer -> Buffer [-> Bool] -> Maybe Buffer +``` + +Returns `null` if result is at infinity. + +##### Throws: + +- `Expected Point` if `!isPoint(A)` +- `Expected Tweak` if `tweak` is not in `[0...order - 1]` + +### privateAdd (d, tweak) + +```haskell +privateAdd :: Buffer -> Buffer -> Maybe Buffer +``` + +Returns `null` if result is equal to `0`. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` +- `Expected Tweak` if `tweak` is not in `[0...order - 1]` + +### privateSub (d, tweak) + +```haskell +privateSub :: Buffer -> Buffer -> Maybe Buffer +``` + +Returns `null` if result is equal to `0`. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` +- `Expected Tweak` if `tweak` is not in `[0...order - 1]` + +### privateNegate (d) + +```haskell +privateNegate :: Buffer -> Buffer +``` + +Returns the negation of d on the order n (`n - d`) + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` + +### xOnlyPointAddTweak (p, tweak) + +```haskell +xOnlyPointAddTweak :: Buffer -> Buffer -> { parity: 1 | 0; xOnlyPubkey: Buffer; } +``` + +Returns the tweaked xOnlyPubkey along with the parity bit (number type of 1|0) + +##### Throws: + +- `Expected Point` if `!isXOnlyPoint(p)` +- `Expected Tweak` if `!isXOnlyPoint(tweak)` + +### xOnlyPointAddTweakCheck (p1, p2, tweak[, tweakParity]) + +```haskell +xOnlyPointAddTweakCheck :: Buffer -> Buffer -> Buffer [-> 1 | 0] -> Bool +``` + +Checks the tweaked pubkey (p2) against the original pubkey (p1) and tweak. +This is slightly slower if you include tweakParity, tweakParity will make it +faster for aggregation later on. + +##### Throws: + +- `Expected Point` if `!isXOnlyPoint(p1)` +- `Expected Point` if `!isXOnlyPoint(p2)` +- `Expected Tweak` if `!isXOnlyPoint(tweak)` +- `Expected Parity` if `tweakParity is not 1 or 0` + +### sign (h, d[, e]) + +```haskell +sign :: Buffer -> Buffer [-> Buffer] -> Buffer +``` + +Returns normalized signatures, each of (r, s) values are guaranteed to less than `order / 2`. +Uses RFC6979. +Adds `e` as Added Entropy to the deterministic k generation. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` +- `Expected Scalar` if `h` is not 256-bit +- `Expected Extra Data (32 bytes)` if `e` is not 256-bit + +### signRecoverable (h, d[, e]) + +```haskell +signRecoverable :: Buffer -> Buffer [-> Buffer] -> { recoveryId: 0 | 1 | 2 | 3; signature: Buffer; } +``` + +Returns normalized signatures and recovery Id, each of (r, s) values are guaranteed to less than `order / 2`. +Uses RFC6979. +Adds `e` as Added Entropy to the deterministic k generation. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` +- `Expected Scalar` if `h` is not 256-bit +- `Expected Extra Data (32 bytes)` if `e` is not 256-bit + +### signSchnorr (h, d[, e]) + +```haskell +signSchnorr :: Buffer -> Buffer [-> Buffer] -> Buffer +``` + +Returns normalized schnorr signature. +Uses BIP340 nonce generation. +Adds `e` as Added Entropy. + +##### Throws: + +- `Expected Private` if `!isPrivate(d)` +- `Expected Scalar` if `h` is not 256-bit +- `Expected Extra Data (32 bytes)` if `e` is not 256-bit + +### verify (h, Q, signature[, strict = false]) + +```haskell +verify :: Buffer -> Buffer -> Buffer [-> Bool] -> Bool +``` + +Returns `false` if any of (r, s) values are equal to `0`, or if the signature is rejected. + +If `strict` is `true`, valid signatures with any of (r, s) values greater than `order / 2` are rejected. + +##### Throws: + +- `Expected Point` if `!isPoint(Q)` +- `Expected Signature` if `signature` has any (r, s) values not in range `[0...order - 1]` +- `Expected Scalar` if `h` is not 256-bit + +### recover (h, signature, recoveryId[, compressed = false]) + +```haskell +verify :: Buffer -> Buffer -> Number [-> Bool] -> Maybe Buffer +``` + +Returns the ECDSA public key from a signature if it can be recovered, `null` otherwise. + + +##### Throws: + +- `Expected Signature` if `signature` has any (r, s) values not in range `(0...order - 1]` +- `Bad Recovery Id` if `recid & 2 !== 0` and `signature` has any r value not in range `(0...P - N - 1]` +- `Expected Hash` if `h` is not 256-bit + + +### verifySchnorr (h, Q, signature) + +```haskell +verifySchnorr :: Buffer -> Buffer -> Buffer -> Bool +``` + +Returns `false` if any of (r, s) values are equal to `0`, or if the signature is rejected. + +##### Throws: + +- `Expected Point` if `!isPoint(Q)` +- `Expected Signature` if `signature` has any (r, s) values not in range `[0...order - 1]` +- `Expected Scalar` if `h` is not 256-bit + +## Credit + +This library uses the native library [secp256k1](https://github.com/bitcoin-core/secp256k1) by the bitcoin-core developers through Rust crate [secp256k1-sys](https://crates.io/crates/secp256k1-sys), including derivatives of its tests and test vectors. + +# LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/index.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/index.cjs new file mode 100644 index 0000000..445fa5f --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/index.cjs @@ -0,0 +1,387 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySchnorr = exports.recover = exports.verify = exports.signSchnorr = exports.signRecoverable = exports.sign = exports.xOnlyPointAddTweakCheck = exports.xOnlyPointAddTweak = exports.privateNegate = exports.privateSub = exports.privateAdd = exports.pointMultiply = exports.xOnlyPointFromPoint = exports.xOnlyPointFromScalar = exports.pointFromScalar = exports.pointCompress = exports.pointAddScalar = exports.pointAdd = exports.isPrivate = exports.isXOnlyPoint = exports.isPointCompressed = exports.isPoint = exports.__initializeContext = void 0; +const uint8array_tools_1 = require("uint8array-tools"); +const validate = require("./validate.cjs"); +const wasm_loader_js_1 = require("./wasm_loader.cjs"); +const WASM_BUFFER = new Uint8Array(wasm_loader_js_1.default.memory.buffer); +const WASM_PRIVATE_KEY_PTR = wasm_loader_js_1.default.PRIVATE_INPUT.value; +const WASM_PUBLIC_KEY_INPUT_PTR = wasm_loader_js_1.default.PUBLIC_KEY_INPUT.value; +const WASM_PUBLIC_KEY_INPUT_PTR2 = wasm_loader_js_1.default.PUBLIC_KEY_INPUT2.value; +const WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR = wasm_loader_js_1.default.X_ONLY_PUBLIC_KEY_INPUT.value; +const WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR = wasm_loader_js_1.default.X_ONLY_PUBLIC_KEY_INPUT2.value; +const WASM_TWEAK_INPUT_PTR = wasm_loader_js_1.default.TWEAK_INPUT.value; +const WASM_HASH_INPUT_PTR = wasm_loader_js_1.default.HASH_INPUT.value; +const WASM_EXTRA_DATA_INPUT_PTR = wasm_loader_js_1.default.EXTRA_DATA_INPUT.value; +const WASM_SIGNATURE_INPUT_PTR = wasm_loader_js_1.default.SIGNATURE_INPUT.value; +const PRIVATE_KEY_INPUT = WASM_BUFFER.subarray(WASM_PRIVATE_KEY_PTR, WASM_PRIVATE_KEY_PTR + validate.PRIVATE_KEY_SIZE); +const PUBLIC_KEY_INPUT = WASM_BUFFER.subarray(WASM_PUBLIC_KEY_INPUT_PTR, WASM_PUBLIC_KEY_INPUT_PTR + validate.PUBLIC_KEY_UNCOMPRESSED_SIZE); +const PUBLIC_KEY_INPUT2 = WASM_BUFFER.subarray(WASM_PUBLIC_KEY_INPUT_PTR2, WASM_PUBLIC_KEY_INPUT_PTR2 + validate.PUBLIC_KEY_UNCOMPRESSED_SIZE); +const X_ONLY_PUBLIC_KEY_INPUT = WASM_BUFFER.subarray(WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR, WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR + validate.X_ONLY_PUBLIC_KEY_SIZE); +const X_ONLY_PUBLIC_KEY_INPUT2 = WASM_BUFFER.subarray(WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR, WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR + validate.X_ONLY_PUBLIC_KEY_SIZE); +const TWEAK_INPUT = WASM_BUFFER.subarray(WASM_TWEAK_INPUT_PTR, WASM_TWEAK_INPUT_PTR + validate.TWEAK_SIZE); +const HASH_INPUT = WASM_BUFFER.subarray(WASM_HASH_INPUT_PTR, WASM_HASH_INPUT_PTR + validate.HASH_SIZE); +const EXTRA_DATA_INPUT = WASM_BUFFER.subarray(WASM_EXTRA_DATA_INPUT_PTR, WASM_EXTRA_DATA_INPUT_PTR + validate.EXTRA_DATA_SIZE); +const SIGNATURE_INPUT = WASM_BUFFER.subarray(WASM_SIGNATURE_INPUT_PTR, WASM_SIGNATURE_INPUT_PTR + validate.SIGNATURE_SIZE); +function assumeCompression(compressed, p) { + if (compressed === undefined) { + return p !== undefined ? p.length : validate.PUBLIC_KEY_COMPRESSED_SIZE; + } + return compressed + ? validate.PUBLIC_KEY_COMPRESSED_SIZE + : validate.PUBLIC_KEY_UNCOMPRESSED_SIZE; +} +function _isPoint(p) { + try { + PUBLIC_KEY_INPUT.set(p); + return wasm_loader_js_1.default.isPoint(p.length) === 1; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + } +} +function __initializeContext() { + wasm_loader_js_1.default.initializeContext(); +} +exports.__initializeContext = __initializeContext; +function isPoint(p) { + return validate.isDERPoint(p) && _isPoint(p); +} +exports.isPoint = isPoint; +function isPointCompressed(p) { + return validate.isPointCompressed(p) && _isPoint(p); +} +exports.isPointCompressed = isPointCompressed; +function isXOnlyPoint(p) { + return validate.isXOnlyPoint(p) && _isPoint(p); +} +exports.isXOnlyPoint = isXOnlyPoint; +function isPrivate(d) { + return validate.isPrivate(d); +} +exports.isPrivate = isPrivate; +function pointAdd(pA, pB, compressed) { + validate.validatePoint(pA); + validate.validatePoint(pB); + const outputlen = assumeCompression(compressed, pA); + try { + PUBLIC_KEY_INPUT.set(pA); + PUBLIC_KEY_INPUT2.set(pB); + return wasm_loader_js_1.default.pointAdd(pA.length, pB.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + PUBLIC_KEY_INPUT2.fill(0); + } +} +exports.pointAdd = pointAdd; +function pointAddScalar(p, tweak, compressed) { + validate.validatePoint(p); + validate.validateTweak(tweak); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + return wasm_loader_js_1.default.pointAddScalar(p.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.pointAddScalar = pointAddScalar; +function pointCompress(p, compressed) { + validate.validatePoint(p); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + wasm_loader_js_1.default.pointCompress(p.length, outputlen); + return PUBLIC_KEY_INPUT.slice(0, outputlen); + } + finally { + PUBLIC_KEY_INPUT.fill(0); + } +} +exports.pointCompress = pointCompress; +function pointFromScalar(d, compressed) { + validate.validatePrivate(d); + const outputlen = assumeCompression(compressed); + try { + PRIVATE_KEY_INPUT.set(d); + return wasm_loader_js_1.default.pointFromScalar(outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + } +} +exports.pointFromScalar = pointFromScalar; +function xOnlyPointFromScalar(d) { + validate.validatePrivate(d); + try { + PRIVATE_KEY_INPUT.set(d); + wasm_loader_js_1.default.xOnlyPointFromScalar(); + return X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + } + finally { + PRIVATE_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + } +} +exports.xOnlyPointFromScalar = xOnlyPointFromScalar; +function xOnlyPointFromPoint(p) { + validate.validatePoint(p); + try { + PUBLIC_KEY_INPUT.set(p); + wasm_loader_js_1.default.xOnlyPointFromPoint(p.length); + return X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + } + finally { + PUBLIC_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + } +} +exports.xOnlyPointFromPoint = xOnlyPointFromPoint; +function pointMultiply(p, tweak, compressed) { + validate.validatePoint(p); + validate.validateTweak(tweak); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + return wasm_loader_js_1.default.pointMultiply(p.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.pointMultiply = pointMultiply; +function privateAdd(d, tweak) { + validate.validatePrivate(d); + validate.validateTweak(tweak); + try { + PRIVATE_KEY_INPUT.set(d); + TWEAK_INPUT.set(tweak); + return wasm_loader_js_1.default.privateAdd() === 1 + ? PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.privateAdd = privateAdd; +function privateSub(d, tweak) { + validate.validatePrivate(d); + validate.validateTweak(tweak); + // We can not pass zero tweak to WASM, because WASM use `secp256k1_ec_seckey_negate` for tweak negate. + // (zero is not valid seckey) + if (validate.isZero(tweak)) { + return new Uint8Array(d); + } + try { + PRIVATE_KEY_INPUT.set(d); + TWEAK_INPUT.set(tweak); + return wasm_loader_js_1.default.privateSub() === 1 + ? PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.privateSub = privateSub; +function privateNegate(d) { + validate.validatePrivate(d); + try { + PRIVATE_KEY_INPUT.set(d); + wasm_loader_js_1.default.privateNegate(); + return PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE); + } + finally { + PRIVATE_KEY_INPUT.fill(0); + } +} +exports.privateNegate = privateNegate; +function xOnlyPointAddTweak(p, tweak) { + validate.validateXOnlyPoint(p); + validate.validateTweak(tweak); + try { + X_ONLY_PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + const parity = wasm_loader_js_1.default.xOnlyPointAddTweak(); + return parity !== -1 + ? { + parity, + xOnlyPubkey: X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE), + } + : null; + } + finally { + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.xOnlyPointAddTweak = xOnlyPointAddTweak; +function xOnlyPointAddTweakCheck(point, tweak, resultToCheck, tweakParity) { + validate.validateXOnlyPoint(point); + validate.validateXOnlyPoint(resultToCheck); + validate.validateTweak(tweak); + const hasParity = tweakParity !== undefined; + if (hasParity) + validate.validateParity(tweakParity); + try { + X_ONLY_PUBLIC_KEY_INPUT.set(point); + X_ONLY_PUBLIC_KEY_INPUT2.set(resultToCheck); + TWEAK_INPUT.set(tweak); + if (hasParity) { + return wasm_loader_js_1.default.xOnlyPointAddTweakCheck(tweakParity) === 1; + } + else { + wasm_loader_js_1.default.xOnlyPointAddTweak(); + const newKey = X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + return (0, uint8array_tools_1.compare)(newKey, resultToCheck) === 0; + } + } + finally { + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT2.fill(0); + TWEAK_INPUT.fill(0); + } +} +exports.xOnlyPointAddTweakCheck = xOnlyPointAddTweakCheck; +function sign(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + wasm_loader_js_1.default.sign(e === undefined ? 0 : 1); + return SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +exports.sign = sign; +function signRecoverable(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + const recoveryId = wasm_loader_js_1.default.signRecoverable(e === undefined ? 0 : 1); + const signature = SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + return { + signature, + recoveryId, + }; + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +exports.signRecoverable = signRecoverable; +function signSchnorr(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + wasm_loader_js_1.default.signSchnorr(e === undefined ? 0 : 1); + return SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +exports.signSchnorr = signSchnorr; +function verify(h, Q, signature, strict = false) { + validate.validateHash(h); + validate.validatePoint(Q); + validate.validateSignature(signature); + try { + HASH_INPUT.set(h); + PUBLIC_KEY_INPUT.set(Q); + SIGNATURE_INPUT.set(signature); + return wasm_loader_js_1.default.verify(Q.length, strict === true ? 1 : 0) === 1 ? true : false; + } + finally { + HASH_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +exports.verify = verify; +function recover(h, signature, recoveryId, compressed = false) { + validate.validateHash(h); + validate.validateSignature(signature); + validate.validateSignatureNonzeroRS(signature); + if (recoveryId & 2) { + validate.validateSigrPMinusN(signature); + } + validate.validateSignatureCustom(() => isXOnlyPoint(signature.subarray(0, 32))); + const outputlen = assumeCompression(compressed); + try { + HASH_INPUT.set(h); + SIGNATURE_INPUT.set(signature); + return wasm_loader_js_1.default.recover(outputlen, recoveryId) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + HASH_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + } +} +exports.recover = recover; +function verifySchnorr(h, Q, signature) { + validate.validateHash(h); + validate.validateXOnlyPoint(Q); + validate.validateSignature(signature); + try { + HASH_INPUT.set(h); + X_ONLY_PUBLIC_KEY_INPUT.set(Q); + SIGNATURE_INPUT.set(signature); + return wasm_loader_js_1.default.verifySchnorr() === 1 ? true : false; + } + finally { + HASH_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +exports.verifySchnorr = verifySchnorr; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.browser.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.browser.cjs new file mode 100644 index 0000000..1d25b40 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.browser.cjs @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateInt32 = void 0; +function get4RandomBytes() { + const bytes = new Uint8Array(4); + if (typeof crypto === "undefined") { + throw new Error("The crypto object is unavailable. This may occur if your environment does not support the Web Cryptography API."); + } + crypto.getRandomValues(bytes); + return bytes; +} +// Only to be used to initialize the context for rust-secp256k1 +function generateInt32() { + const array = get4RandomBytes(); + return ((array[0] << (3 * 8)) + + (array[1] << (2 * 8)) + + (array[2] << (1 * 8)) + + array[3]); +} +exports.generateInt32 = generateInt32; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.cjs new file mode 100644 index 0000000..42382d0 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/rand.cjs @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateInt32 = void 0; +const crypto_1 = require("crypto"); +function generateInt32() { + return (0, crypto_1.randomBytes)(4).readInt32BE(0); +} +exports.generateInt32 = generateInt32; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate.cjs new file mode 100644 index 0000000..3aaa7b6 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate.cjs @@ -0,0 +1,144 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateSigrPMinusN = exports.validateSignatureNonzeroRS = exports.validateSignatureCustom = exports.validateSignature = exports.validateExtraData = exports.validateHash = exports.validateTweak = exports.validateXOnlyPoint = exports.validatePoint = exports.validatePrivate = exports.validateParity = exports.isPointCompressed = exports.isDERPoint = exports.isXOnlyPoint = exports.isPoint = exports.isPrivate = exports.isZero = exports.SIGNATURE_SIZE = exports.EXTRA_DATA_SIZE = exports.HASH_SIZE = exports.TWEAK_SIZE = exports.X_ONLY_PUBLIC_KEY_SIZE = exports.PUBLIC_KEY_UNCOMPRESSED_SIZE = exports.PUBLIC_KEY_COMPRESSED_SIZE = exports.PRIVATE_KEY_SIZE = void 0; +const validate_error_js_1 = require("./validate_error.cjs"); +exports.PRIVATE_KEY_SIZE = 32; +exports.PUBLIC_KEY_COMPRESSED_SIZE = 33; +exports.PUBLIC_KEY_UNCOMPRESSED_SIZE = 65; +exports.X_ONLY_PUBLIC_KEY_SIZE = 32; +exports.TWEAK_SIZE = 32; +exports.HASH_SIZE = 32; +exports.EXTRA_DATA_SIZE = 32; +exports.SIGNATURE_SIZE = 64; +const BN32_ZERO = new Uint8Array(32); +const BN32_N = new Uint8Array([ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 186, 174, 220, 230, 175, 72, 160, 59, 191, 210, 94, 140, 208, 54, 65, 65, +]); +// Difference between field and order +const BN32_P_MINUS_N = new Uint8Array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69, 81, 35, 25, 80, 183, 95, + 196, 64, 45, 161, 114, 47, 201, 186, 238, +]); +function isUint8Array(value) { + return value instanceof Uint8Array; +} +function cmpBN32(data1, data2) { + for (let i = 0; i < 32; ++i) { + if (data1[i] !== data2[i]) { + return data1[i] < data2[i] ? -1 : 1; + } + } + return 0; +} +function isZero(x) { + return cmpBN32(x, BN32_ZERO) === 0; +} +exports.isZero = isZero; +function isPrivate(x) { + return (isUint8Array(x) && + x.length === exports.PRIVATE_KEY_SIZE && + cmpBN32(x, BN32_ZERO) > 0 && + cmpBN32(x, BN32_N) < 0); +} +exports.isPrivate = isPrivate; +function isPoint(p) { + return (isUint8Array(p) && + (p.length === exports.PUBLIC_KEY_COMPRESSED_SIZE || + p.length === exports.PUBLIC_KEY_UNCOMPRESSED_SIZE || + p.length === exports.X_ONLY_PUBLIC_KEY_SIZE)); +} +exports.isPoint = isPoint; +function isXOnlyPoint(p) { + return isUint8Array(p) && p.length === exports.X_ONLY_PUBLIC_KEY_SIZE; +} +exports.isXOnlyPoint = isXOnlyPoint; +function isDERPoint(p) { + return (isUint8Array(p) && + (p.length === exports.PUBLIC_KEY_COMPRESSED_SIZE || + p.length === exports.PUBLIC_KEY_UNCOMPRESSED_SIZE)); +} +exports.isDERPoint = isDERPoint; +function isPointCompressed(p) { + return isUint8Array(p) && p.length === exports.PUBLIC_KEY_COMPRESSED_SIZE; +} +exports.isPointCompressed = isPointCompressed; +function isTweak(tweak) { + return (isUint8Array(tweak) && + tweak.length === exports.TWEAK_SIZE && + cmpBN32(tweak, BN32_N) < 0); +} +function isHash(h) { + return isUint8Array(h) && h.length === exports.HASH_SIZE; +} +function isExtraData(e) { + return e === undefined || (isUint8Array(e) && e.length === exports.EXTRA_DATA_SIZE); +} +function isSignature(signature) { + return (isUint8Array(signature) && + signature.length === 64 && + cmpBN32(signature.subarray(0, 32), BN32_N) < 0 && + cmpBN32(signature.subarray(32, 64), BN32_N) < 0); +} +function isSigrLessThanPMinusN(signature) { + return (isUint8Array(signature) && + signature.length === 64 && + cmpBN32(signature.subarray(0, 32), BN32_P_MINUS_N) < 0); +} +function validateParity(p) { + if (p !== 0 && p !== 1) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_PARITY); +} +exports.validateParity = validateParity; +function validatePrivate(d) { + if (!isPrivate(d)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_PRIVATE); +} +exports.validatePrivate = validatePrivate; +function validatePoint(p) { + if (!isPoint(p)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_POINT); +} +exports.validatePoint = validatePoint; +function validateXOnlyPoint(p) { + if (!isXOnlyPoint(p)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_POINT); +} +exports.validateXOnlyPoint = validateXOnlyPoint; +function validateTweak(tweak) { + if (!isTweak(tweak)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_TWEAK); +} +exports.validateTweak = validateTweak; +function validateHash(h) { + if (!isHash(h)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_HASH); +} +exports.validateHash = validateHash; +function validateExtraData(e) { + if (!isExtraData(e)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_EXTRA_DATA); +} +exports.validateExtraData = validateExtraData; +function validateSignature(signature) { + if (!isSignature(signature)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_SIGNATURE); +} +exports.validateSignature = validateSignature; +function validateSignatureCustom(validatorFn) { + if (!validatorFn()) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_SIGNATURE); +} +exports.validateSignatureCustom = validateSignatureCustom; +function validateSignatureNonzeroRS(signature) { + if (isZero(signature.subarray(0, 32))) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_SIGNATURE); + if (isZero(signature.subarray(32, 64))) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_SIGNATURE); +} +exports.validateSignatureNonzeroRS = validateSignatureNonzeroRS; +function validateSigrPMinusN(signature) { + if (!isSigrLessThanPMinusN(signature)) + (0, validate_error_js_1.throwError)(validate_error_js_1.ERROR_BAD_RECOVERY_ID); +} +exports.validateSigrPMinusN = validateSigrPMinusN; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate_error.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate_error.cjs new file mode 100644 index 0000000..abed850 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/validate_error.cjs @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.throwError = exports.ERROR_BAD_RECOVERY_ID = exports.ERROR_BAD_PARITY = exports.ERROR_BAD_EXTRA_DATA = exports.ERROR_BAD_SIGNATURE = exports.ERROR_BAD_HASH = exports.ERROR_BAD_TWEAK = exports.ERROR_BAD_POINT = exports.ERROR_BAD_PRIVATE = void 0; +exports.ERROR_BAD_PRIVATE = 0; +exports.ERROR_BAD_POINT = 1; +exports.ERROR_BAD_TWEAK = 2; +exports.ERROR_BAD_HASH = 3; +exports.ERROR_BAD_SIGNATURE = 4; +exports.ERROR_BAD_EXTRA_DATA = 5; +exports.ERROR_BAD_PARITY = 6; +exports.ERROR_BAD_RECOVERY_ID = 7; +const ERRORS_MESSAGES = { + [exports.ERROR_BAD_PRIVATE.toString()]: "Expected Private", + [exports.ERROR_BAD_POINT.toString()]: "Expected Point", + [exports.ERROR_BAD_TWEAK.toString()]: "Expected Tweak", + [exports.ERROR_BAD_HASH.toString()]: "Expected Hash", + [exports.ERROR_BAD_SIGNATURE.toString()]: "Expected Signature", + [exports.ERROR_BAD_EXTRA_DATA.toString()]: "Expected Extra Data (32 bytes)", + [exports.ERROR_BAD_PARITY.toString()]: "Expected Parity (1 | 0)", + [exports.ERROR_BAD_RECOVERY_ID.toString()]: "Bad Recovery Id", +}; +function throwError(errcode) { + const message = ERRORS_MESSAGES[errcode.toString()] || `Unknow error code: ${errcode}`; + throw new TypeError(message); +} +exports.throwError = throwError; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.browser.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.browser.cjs new file mode 100644 index 0000000..77543b1 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.browser.cjs @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// Suppress TS2792: Cannot find module './secp256k1.wasm'. +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const wasm = require("./secp256k1.wasm"); +exports.default = wasm; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.cjs new file mode 100644 index 0000000..80f0a69 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.cjs @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = require("fs"); +const wasm_path_cjs_js_1 = require("./wasm_path_cjs.cjs"); +const rand = require("./rand.cjs"); +const validate_error = require("./validate_error.cjs"); +const binary = (0, fs_1.readFileSync)((0, wasm_path_cjs_js_1.path)("secp256k1.wasm")); +const imports = { + "./rand.js": rand, + "./validate_error.js": validate_error, +}; +const mod = new WebAssembly.Module(binary); +const instance = new WebAssembly.Instance(mod, imports); +exports.default = instance.exports; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_path_cjs.cjs b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_path_cjs.cjs new file mode 100644 index 0000000..0e24bc1 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/cjs/wasm_path_cjs.cjs @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.path = void 0; +const nodePath = require("path"); +function path(wasmFilename) { + // Since we know this file will only be used by cjs + // and we know that wasm file will always be in the parent dir + // We can translate to the parent directory without problem + const pathname = nodePath.join(__dirname, "..", wasmFilename); + return pathname; +} +exports.path = path; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/index.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/index.d.ts new file mode 100644 index 0000000..24551f8 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/index.d.ts @@ -0,0 +1,33 @@ +export declare function __initializeContext(): void; +export declare function isPoint(p: Uint8Array): boolean; +export declare function isPointCompressed(p: Uint8Array): boolean; +export declare function isXOnlyPoint(p: Uint8Array): boolean; +export declare function isPrivate(d: Uint8Array): boolean; +export declare function pointAdd(pA: Uint8Array, pB: Uint8Array, compressed?: boolean): Uint8Array | null; +export declare function pointAddScalar(p: Uint8Array, tweak: Uint8Array, compressed?: boolean): Uint8Array | null; +export declare function pointCompress(p: Uint8Array, compressed?: boolean): Uint8Array; +export declare function pointFromScalar(d: Uint8Array, compressed?: boolean): Uint8Array | null; +export declare function xOnlyPointFromScalar(d: Uint8Array): Uint8Array; +export declare function xOnlyPointFromPoint(p: Uint8Array): Uint8Array; +export declare function pointMultiply(p: Uint8Array, tweak: Uint8Array, compressed?: boolean): Uint8Array | null; +export declare function privateAdd(d: Uint8Array, tweak: Uint8Array): Uint8Array | null; +export declare function privateSub(d: Uint8Array, tweak: Uint8Array): Uint8Array | null; +export declare function privateNegate(d: Uint8Array): Uint8Array; +export interface XOnlyPointAddTweakResult { + parity: 1 | 0; + xOnlyPubkey: Uint8Array; +} +export declare function xOnlyPointAddTweak(p: Uint8Array, tweak: Uint8Array): XOnlyPointAddTweakResult | null; +export declare type TweakParity = 1 | 0; +export declare function xOnlyPointAddTweakCheck(point: Uint8Array, tweak: Uint8Array, resultToCheck: Uint8Array, tweakParity?: TweakParity): boolean; +export declare function sign(h: Uint8Array, d: Uint8Array, e?: Uint8Array): Uint8Array; +export interface RecoverableSignature { + signature: Uint8Array; + recoveryId: RecoveryIdType; +} +export declare function signRecoverable(h: Uint8Array, d: Uint8Array, e?: Uint8Array): RecoverableSignature; +export declare function signSchnorr(h: Uint8Array, d: Uint8Array, e?: Uint8Array): Uint8Array; +export declare function verify(h: Uint8Array, Q: Uint8Array, signature: Uint8Array, strict?: boolean): boolean; +export declare type RecoveryIdType = 0 | 1 | 2 | 3; +export declare function recover(h: Uint8Array, signature: Uint8Array, recoveryId: RecoveryIdType, compressed?: boolean): Uint8Array | null; +export declare function verifySchnorr(h: Uint8Array, Q: Uint8Array, signature: Uint8Array): boolean; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/index.js b/src/libMPC/node_modules/tiny-secp256k1/lib/index.js new file mode 100644 index 0000000..0524817 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/index.js @@ -0,0 +1,361 @@ +import { compare } from "uint8array-tools"; +import * as validate from "./validate.js"; +import wasm from "./wasm_loader.js"; +const WASM_BUFFER = new Uint8Array(wasm.memory.buffer); +const WASM_PRIVATE_KEY_PTR = wasm.PRIVATE_INPUT.value; +const WASM_PUBLIC_KEY_INPUT_PTR = wasm.PUBLIC_KEY_INPUT.value; +const WASM_PUBLIC_KEY_INPUT_PTR2 = wasm.PUBLIC_KEY_INPUT2.value; +const WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR = wasm.X_ONLY_PUBLIC_KEY_INPUT.value; +const WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR = wasm.X_ONLY_PUBLIC_KEY_INPUT2.value; +const WASM_TWEAK_INPUT_PTR = wasm.TWEAK_INPUT.value; +const WASM_HASH_INPUT_PTR = wasm.HASH_INPUT.value; +const WASM_EXTRA_DATA_INPUT_PTR = wasm.EXTRA_DATA_INPUT.value; +const WASM_SIGNATURE_INPUT_PTR = wasm.SIGNATURE_INPUT.value; +const PRIVATE_KEY_INPUT = WASM_BUFFER.subarray(WASM_PRIVATE_KEY_PTR, WASM_PRIVATE_KEY_PTR + validate.PRIVATE_KEY_SIZE); +const PUBLIC_KEY_INPUT = WASM_BUFFER.subarray(WASM_PUBLIC_KEY_INPUT_PTR, WASM_PUBLIC_KEY_INPUT_PTR + validate.PUBLIC_KEY_UNCOMPRESSED_SIZE); +const PUBLIC_KEY_INPUT2 = WASM_BUFFER.subarray(WASM_PUBLIC_KEY_INPUT_PTR2, WASM_PUBLIC_KEY_INPUT_PTR2 + validate.PUBLIC_KEY_UNCOMPRESSED_SIZE); +const X_ONLY_PUBLIC_KEY_INPUT = WASM_BUFFER.subarray(WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR, WASM_X_ONLY_PUBLIC_KEY_INPUT_PTR + validate.X_ONLY_PUBLIC_KEY_SIZE); +const X_ONLY_PUBLIC_KEY_INPUT2 = WASM_BUFFER.subarray(WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR, WASM_X_ONLY_PUBLIC_KEY_INPUT2_PTR + validate.X_ONLY_PUBLIC_KEY_SIZE); +const TWEAK_INPUT = WASM_BUFFER.subarray(WASM_TWEAK_INPUT_PTR, WASM_TWEAK_INPUT_PTR + validate.TWEAK_SIZE); +const HASH_INPUT = WASM_BUFFER.subarray(WASM_HASH_INPUT_PTR, WASM_HASH_INPUT_PTR + validate.HASH_SIZE); +const EXTRA_DATA_INPUT = WASM_BUFFER.subarray(WASM_EXTRA_DATA_INPUT_PTR, WASM_EXTRA_DATA_INPUT_PTR + validate.EXTRA_DATA_SIZE); +const SIGNATURE_INPUT = WASM_BUFFER.subarray(WASM_SIGNATURE_INPUT_PTR, WASM_SIGNATURE_INPUT_PTR + validate.SIGNATURE_SIZE); +function assumeCompression(compressed, p) { + if (compressed === undefined) { + return p !== undefined ? p.length : validate.PUBLIC_KEY_COMPRESSED_SIZE; + } + return compressed + ? validate.PUBLIC_KEY_COMPRESSED_SIZE + : validate.PUBLIC_KEY_UNCOMPRESSED_SIZE; +} +function _isPoint(p) { + try { + PUBLIC_KEY_INPUT.set(p); + return wasm.isPoint(p.length) === 1; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + } +} +export function __initializeContext() { + wasm.initializeContext(); +} +export function isPoint(p) { + return validate.isDERPoint(p) && _isPoint(p); +} +export function isPointCompressed(p) { + return validate.isPointCompressed(p) && _isPoint(p); +} +export function isXOnlyPoint(p) { + return validate.isXOnlyPoint(p) && _isPoint(p); +} +export function isPrivate(d) { + return validate.isPrivate(d); +} +export function pointAdd(pA, pB, compressed) { + validate.validatePoint(pA); + validate.validatePoint(pB); + const outputlen = assumeCompression(compressed, pA); + try { + PUBLIC_KEY_INPUT.set(pA); + PUBLIC_KEY_INPUT2.set(pB); + return wasm.pointAdd(pA.length, pB.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + PUBLIC_KEY_INPUT2.fill(0); + } +} +export function pointAddScalar(p, tweak, compressed) { + validate.validatePoint(p); + validate.validateTweak(tweak); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + return wasm.pointAddScalar(p.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function pointCompress(p, compressed) { + validate.validatePoint(p); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + wasm.pointCompress(p.length, outputlen); + return PUBLIC_KEY_INPUT.slice(0, outputlen); + } + finally { + PUBLIC_KEY_INPUT.fill(0); + } +} +export function pointFromScalar(d, compressed) { + validate.validatePrivate(d); + const outputlen = assumeCompression(compressed); + try { + PRIVATE_KEY_INPUT.set(d); + return wasm.pointFromScalar(outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + } +} +export function xOnlyPointFromScalar(d) { + validate.validatePrivate(d); + try { + PRIVATE_KEY_INPUT.set(d); + wasm.xOnlyPointFromScalar(); + return X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + } + finally { + PRIVATE_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + } +} +export function xOnlyPointFromPoint(p) { + validate.validatePoint(p); + try { + PUBLIC_KEY_INPUT.set(p); + wasm.xOnlyPointFromPoint(p.length); + return X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + } + finally { + PUBLIC_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + } +} +export function pointMultiply(p, tweak, compressed) { + validate.validatePoint(p); + validate.validateTweak(tweak); + const outputlen = assumeCompression(compressed, p); + try { + PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + return wasm.pointMultiply(p.length, outputlen) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function privateAdd(d, tweak) { + validate.validatePrivate(d); + validate.validateTweak(tweak); + try { + PRIVATE_KEY_INPUT.set(d); + TWEAK_INPUT.set(tweak); + return wasm.privateAdd() === 1 + ? PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function privateSub(d, tweak) { + validate.validatePrivate(d); + validate.validateTweak(tweak); + // We can not pass zero tweak to WASM, because WASM use `secp256k1_ec_seckey_negate` for tweak negate. + // (zero is not valid seckey) + if (validate.isZero(tweak)) { + return new Uint8Array(d); + } + try { + PRIVATE_KEY_INPUT.set(d); + TWEAK_INPUT.set(tweak); + return wasm.privateSub() === 1 + ? PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE) + : null; + } + finally { + PRIVATE_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function privateNegate(d) { + validate.validatePrivate(d); + try { + PRIVATE_KEY_INPUT.set(d); + wasm.privateNegate(); + return PRIVATE_KEY_INPUT.slice(0, validate.PRIVATE_KEY_SIZE); + } + finally { + PRIVATE_KEY_INPUT.fill(0); + } +} +export function xOnlyPointAddTweak(p, tweak) { + validate.validateXOnlyPoint(p); + validate.validateTweak(tweak); + try { + X_ONLY_PUBLIC_KEY_INPUT.set(p); + TWEAK_INPUT.set(tweak); + const parity = wasm.xOnlyPointAddTweak(); + return parity !== -1 + ? { + parity, + xOnlyPubkey: X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE), + } + : null; + } + finally { + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function xOnlyPointAddTweakCheck(point, tweak, resultToCheck, tweakParity) { + validate.validateXOnlyPoint(point); + validate.validateXOnlyPoint(resultToCheck); + validate.validateTweak(tweak); + const hasParity = tweakParity !== undefined; + if (hasParity) + validate.validateParity(tweakParity); + try { + X_ONLY_PUBLIC_KEY_INPUT.set(point); + X_ONLY_PUBLIC_KEY_INPUT2.set(resultToCheck); + TWEAK_INPUT.set(tweak); + if (hasParity) { + return wasm.xOnlyPointAddTweakCheck(tweakParity) === 1; + } + else { + wasm.xOnlyPointAddTweak(); + const newKey = X_ONLY_PUBLIC_KEY_INPUT.slice(0, validate.X_ONLY_PUBLIC_KEY_SIZE); + return compare(newKey, resultToCheck) === 0; + } + } + finally { + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT2.fill(0); + TWEAK_INPUT.fill(0); + } +} +export function sign(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + wasm.sign(e === undefined ? 0 : 1); + return SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +export function signRecoverable(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + const recoveryId = wasm.signRecoverable(e === undefined ? 0 : 1); + const signature = SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + return { + signature, + recoveryId, + }; + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +export function signSchnorr(h, d, e) { + validate.validateHash(h); + validate.validatePrivate(d); + validate.validateExtraData(e); + try { + HASH_INPUT.set(h); + PRIVATE_KEY_INPUT.set(d); + if (e !== undefined) + EXTRA_DATA_INPUT.set(e); + wasm.signSchnorr(e === undefined ? 0 : 1); + return SIGNATURE_INPUT.slice(0, validate.SIGNATURE_SIZE); + } + finally { + HASH_INPUT.fill(0); + PRIVATE_KEY_INPUT.fill(0); + if (e !== undefined) + EXTRA_DATA_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +export function verify(h, Q, signature, strict = false) { + validate.validateHash(h); + validate.validatePoint(Q); + validate.validateSignature(signature); + try { + HASH_INPUT.set(h); + PUBLIC_KEY_INPUT.set(Q); + SIGNATURE_INPUT.set(signature); + return wasm.verify(Q.length, strict === true ? 1 : 0) === 1 ? true : false; + } + finally { + HASH_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} +export function recover(h, signature, recoveryId, compressed = false) { + validate.validateHash(h); + validate.validateSignature(signature); + validate.validateSignatureNonzeroRS(signature); + if (recoveryId & 2) { + validate.validateSigrPMinusN(signature); + } + validate.validateSignatureCustom(() => isXOnlyPoint(signature.subarray(0, 32))); + const outputlen = assumeCompression(compressed); + try { + HASH_INPUT.set(h); + SIGNATURE_INPUT.set(signature); + return wasm.recover(outputlen, recoveryId) === 1 + ? PUBLIC_KEY_INPUT.slice(0, outputlen) + : null; + } + finally { + HASH_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + PUBLIC_KEY_INPUT.fill(0); + } +} +export function verifySchnorr(h, Q, signature) { + validate.validateHash(h); + validate.validateXOnlyPoint(Q); + validate.validateSignature(signature); + try { + HASH_INPUT.set(h); + X_ONLY_PUBLIC_KEY_INPUT.set(Q); + SIGNATURE_INPUT.set(signature); + return wasm.verifySchnorr() === 1 ? true : false; + } + finally { + HASH_INPUT.fill(0); + X_ONLY_PUBLIC_KEY_INPUT.fill(0); + SIGNATURE_INPUT.fill(0); + } +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.d.ts new file mode 100644 index 0000000..5a29417 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.d.ts @@ -0,0 +1 @@ +export declare function generateInt32(): number; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.js b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.js new file mode 100644 index 0000000..bb07966 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.browser.js @@ -0,0 +1,16 @@ +function get4RandomBytes() { + const bytes = new Uint8Array(4); + if (typeof crypto === "undefined") { + throw new Error("The crypto object is unavailable. This may occur if your environment does not support the Web Cryptography API."); + } + crypto.getRandomValues(bytes); + return bytes; +} +// Only to be used to initialize the context for rust-secp256k1 +export function generateInt32() { + const array = get4RandomBytes(); + return ((array[0] << (3 * 8)) + + (array[1] << (2 * 8)) + + (array[2] << (1 * 8)) + + array[3]); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/rand.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.d.ts new file mode 100644 index 0000000..5a29417 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.d.ts @@ -0,0 +1 @@ +export declare function generateInt32(): number; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/rand.js b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.js new file mode 100644 index 0000000..8730c0d --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/rand.js @@ -0,0 +1,4 @@ +import { randomBytes } from "crypto"; +export function generateInt32() { + return randomBytes(4).readInt32BE(0); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/secp256k1.wasm b/src/libMPC/node_modules/tiny-secp256k1/lib/secp256k1.wasm new file mode 100644 index 0000000000000000000000000000000000000000..7948a4c1862f30b3e5700af9d1b28998c984a35c GIT binary patch literal 163363 zcmeFa3!EHBb?@KZ^W2?%%swQow0iW6WP2rBw*1n{4{Y^-A3QDy<2dBLYy(bUWx$dZ zL+(em25W6ZATSPwIM4qOAXWk<6P(MRdv>&viAdmH4BDwaU0rqR)Tv*cQ+2A_yYyo{I4`$5Lbdw$0EGJ%&V`XgNO&-48p z|L10==y^dVA9#VE5BQfK4|t|nB<~p46nO_#G|d>f?s^SLWyQ4=V8;_iC1pn4fo>oL@9QJ$?#*m#yYsdD|;reeg#DZ|W7Vdc~nv z(C+_o+cRJNszbNE_K-JHc*ULjUj2$!9r8xY`@XOCyk|f2=I37X12;eW`TM@_#*AOQ zLvBScdzn|78oYZ^CYW%yU-Z&jZ@=}RH&(jw`>%1I{qXIFUUA3mKjO`d-f{31 zccC;Ql3920q91;Vw`SbldH!ub#C>mV_Rd%Q(5t+4qt{0-y53e@C|~p98*hkiepYm2 zWJ$%z7d`vB=SMew-wlqxkx6;*hTC5H>bp?bm)w4vH&+tMi(dNjSH1e+L2rE?`YV3$ zN4yP%gC>(VKW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6Gb; zHH#zU5DZ25e`)&9!C1Q?nhr=f@fkn)jT&Cgi*_Cue-LYRGWBb*gm6BX;kVCVcy;4% zv|)(HtV$?kqQU=V$G(dg$1@pZ+tthua7ILjtYv~63W7^kw8Nm&D^q2xEF`JGz|6ux z|F2jD66{T+f(2y=gaM*Ka5S_xH+9rEGyPZGIe<_jSUWiy8d;grnp@c#8Cp3|L;Y7& J(th8p{{wIHc>DkW literal 0 HcmV?d00001 diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/validate.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/validate.d.ts new file mode 100644 index 0000000..90b756c --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/validate.d.ts @@ -0,0 +1,25 @@ +export declare const PRIVATE_KEY_SIZE = 32; +export declare const PUBLIC_KEY_COMPRESSED_SIZE = 33; +export declare const PUBLIC_KEY_UNCOMPRESSED_SIZE = 65; +export declare const X_ONLY_PUBLIC_KEY_SIZE = 32; +export declare const TWEAK_SIZE = 32; +export declare const HASH_SIZE = 32; +export declare const EXTRA_DATA_SIZE = 32; +export declare const SIGNATURE_SIZE = 64; +export declare function isZero(x: Uint8Array): boolean; +export declare function isPrivate(x: Uint8Array): boolean; +export declare function isPoint(p: Uint8Array): boolean; +export declare function isXOnlyPoint(p: Uint8Array): boolean; +export declare function isDERPoint(p: Uint8Array): boolean; +export declare function isPointCompressed(p: Uint8Array): boolean; +export declare function validateParity(p: 1 | 0): void; +export declare function validatePrivate(d: Uint8Array): void; +export declare function validatePoint(p: Uint8Array): void; +export declare function validateXOnlyPoint(p: Uint8Array): void; +export declare function validateTweak(tweak: Uint8Array): void; +export declare function validateHash(h: Uint8Array): void; +export declare function validateExtraData(e?: Uint8Array): void; +export declare function validateSignature(signature: Uint8Array): void; +export declare function validateSignatureCustom(validatorFn: () => boolean): void; +export declare function validateSignatureNonzeroRS(signature: Uint8Array): void; +export declare function validateSigrPMinusN(signature: Uint8Array): void; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/validate.js b/src/libMPC/node_modules/tiny-secp256k1/lib/validate.js new file mode 100644 index 0000000..f0837d9 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/validate.js @@ -0,0 +1,124 @@ +import { ERROR_BAD_PRIVATE, ERROR_BAD_POINT, ERROR_BAD_TWEAK, throwError, ERROR_BAD_HASH, ERROR_BAD_EXTRA_DATA, ERROR_BAD_SIGNATURE, ERROR_BAD_PARITY, ERROR_BAD_RECOVERY_ID, } from "./validate_error.js"; +export const PRIVATE_KEY_SIZE = 32; +export const PUBLIC_KEY_COMPRESSED_SIZE = 33; +export const PUBLIC_KEY_UNCOMPRESSED_SIZE = 65; +export const X_ONLY_PUBLIC_KEY_SIZE = 32; +export const TWEAK_SIZE = 32; +export const HASH_SIZE = 32; +export const EXTRA_DATA_SIZE = 32; +export const SIGNATURE_SIZE = 64; +const BN32_ZERO = new Uint8Array(32); +const BN32_N = new Uint8Array([ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 186, 174, 220, 230, 175, 72, 160, 59, 191, 210, 94, 140, 208, 54, 65, 65, +]); +// Difference between field and order +const BN32_P_MINUS_N = new Uint8Array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69, 81, 35, 25, 80, 183, 95, + 196, 64, 45, 161, 114, 47, 201, 186, 238, +]); +function isUint8Array(value) { + return value instanceof Uint8Array; +} +function cmpBN32(data1, data2) { + for (let i = 0; i < 32; ++i) { + if (data1[i] !== data2[i]) { + return data1[i] < data2[i] ? -1 : 1; + } + } + return 0; +} +export function isZero(x) { + return cmpBN32(x, BN32_ZERO) === 0; +} +export function isPrivate(x) { + return (isUint8Array(x) && + x.length === PRIVATE_KEY_SIZE && + cmpBN32(x, BN32_ZERO) > 0 && + cmpBN32(x, BN32_N) < 0); +} +export function isPoint(p) { + return (isUint8Array(p) && + (p.length === PUBLIC_KEY_COMPRESSED_SIZE || + p.length === PUBLIC_KEY_UNCOMPRESSED_SIZE || + p.length === X_ONLY_PUBLIC_KEY_SIZE)); +} +export function isXOnlyPoint(p) { + return isUint8Array(p) && p.length === X_ONLY_PUBLIC_KEY_SIZE; +} +export function isDERPoint(p) { + return (isUint8Array(p) && + (p.length === PUBLIC_KEY_COMPRESSED_SIZE || + p.length === PUBLIC_KEY_UNCOMPRESSED_SIZE)); +} +export function isPointCompressed(p) { + return isUint8Array(p) && p.length === PUBLIC_KEY_COMPRESSED_SIZE; +} +function isTweak(tweak) { + return (isUint8Array(tweak) && + tweak.length === TWEAK_SIZE && + cmpBN32(tweak, BN32_N) < 0); +} +function isHash(h) { + return isUint8Array(h) && h.length === HASH_SIZE; +} +function isExtraData(e) { + return e === undefined || (isUint8Array(e) && e.length === EXTRA_DATA_SIZE); +} +function isSignature(signature) { + return (isUint8Array(signature) && + signature.length === 64 && + cmpBN32(signature.subarray(0, 32), BN32_N) < 0 && + cmpBN32(signature.subarray(32, 64), BN32_N) < 0); +} +function isSigrLessThanPMinusN(signature) { + return (isUint8Array(signature) && + signature.length === 64 && + cmpBN32(signature.subarray(0, 32), BN32_P_MINUS_N) < 0); +} +export function validateParity(p) { + if (p !== 0 && p !== 1) + throwError(ERROR_BAD_PARITY); +} +export function validatePrivate(d) { + if (!isPrivate(d)) + throwError(ERROR_BAD_PRIVATE); +} +export function validatePoint(p) { + if (!isPoint(p)) + throwError(ERROR_BAD_POINT); +} +export function validateXOnlyPoint(p) { + if (!isXOnlyPoint(p)) + throwError(ERROR_BAD_POINT); +} +export function validateTweak(tweak) { + if (!isTweak(tweak)) + throwError(ERROR_BAD_TWEAK); +} +export function validateHash(h) { + if (!isHash(h)) + throwError(ERROR_BAD_HASH); +} +export function validateExtraData(e) { + if (!isExtraData(e)) + throwError(ERROR_BAD_EXTRA_DATA); +} +export function validateSignature(signature) { + if (!isSignature(signature)) + throwError(ERROR_BAD_SIGNATURE); +} +export function validateSignatureCustom(validatorFn) { + if (!validatorFn()) + throwError(ERROR_BAD_SIGNATURE); +} +export function validateSignatureNonzeroRS(signature) { + if (isZero(signature.subarray(0, 32))) + throwError(ERROR_BAD_SIGNATURE); + if (isZero(signature.subarray(32, 64))) + throwError(ERROR_BAD_SIGNATURE); +} +export function validateSigrPMinusN(signature) { + if (!isSigrLessThanPMinusN(signature)) + throwError(ERROR_BAD_RECOVERY_ID); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.d.ts new file mode 100644 index 0000000..bc4a226 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.d.ts @@ -0,0 +1,9 @@ +export declare const ERROR_BAD_PRIVATE = 0; +export declare const ERROR_BAD_POINT = 1; +export declare const ERROR_BAD_TWEAK = 2; +export declare const ERROR_BAD_HASH = 3; +export declare const ERROR_BAD_SIGNATURE = 4; +export declare const ERROR_BAD_EXTRA_DATA = 5; +export declare const ERROR_BAD_PARITY = 6; +export declare const ERROR_BAD_RECOVERY_ID = 7; +export declare function throwError(errcode: number): never; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.js b/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.js new file mode 100644 index 0000000..d609d12 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/validate_error.js @@ -0,0 +1,22 @@ +export const ERROR_BAD_PRIVATE = 0; +export const ERROR_BAD_POINT = 1; +export const ERROR_BAD_TWEAK = 2; +export const ERROR_BAD_HASH = 3; +export const ERROR_BAD_SIGNATURE = 4; +export const ERROR_BAD_EXTRA_DATA = 5; +export const ERROR_BAD_PARITY = 6; +export const ERROR_BAD_RECOVERY_ID = 7; +const ERRORS_MESSAGES = { + [ERROR_BAD_PRIVATE.toString()]: "Expected Private", + [ERROR_BAD_POINT.toString()]: "Expected Point", + [ERROR_BAD_TWEAK.toString()]: "Expected Tweak", + [ERROR_BAD_HASH.toString()]: "Expected Hash", + [ERROR_BAD_SIGNATURE.toString()]: "Expected Signature", + [ERROR_BAD_EXTRA_DATA.toString()]: "Expected Extra Data (32 bytes)", + [ERROR_BAD_PARITY.toString()]: "Expected Parity (1 | 0)", + [ERROR_BAD_RECOVERY_ID.toString()]: "Bad Recovery Id", +}; +export function throwError(errcode) { + const message = ERRORS_MESSAGES[errcode.toString()] || `Unknow error code: ${errcode}`; + throw new TypeError(message); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.d.ts new file mode 100644 index 0000000..3cfdbed --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.d.ts @@ -0,0 +1,2 @@ +import * as wasm from "./secp256k1.wasm"; +export default wasm; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.js b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.js new file mode 100644 index 0000000..bf36a0e --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.browser.js @@ -0,0 +1,5 @@ +// Suppress TS2792: Cannot find module './secp256k1.wasm'. +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import * as wasm from "./secp256k1.wasm"; +export default wasm; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.d.ts new file mode 100644 index 0000000..bf5221a --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.d.ts @@ -0,0 +1,41 @@ +interface WebAssemblyMemory { + buffer: Uint8Array; +} +interface WebAssemblyGlobal { + value: number; +} +declare type RecoveryIdType = 0 | 1 | 2 | 3; +interface Secp256k1WASM { + memory: WebAssemblyMemory; + PRIVATE_INPUT: WebAssemblyGlobal; + PUBLIC_KEY_INPUT: WebAssemblyGlobal; + PUBLIC_KEY_INPUT2: WebAssemblyGlobal; + X_ONLY_PUBLIC_KEY_INPUT: WebAssemblyGlobal; + X_ONLY_PUBLIC_KEY_INPUT2: WebAssemblyGlobal; + TWEAK_INPUT: WebAssemblyGlobal; + HASH_INPUT: WebAssemblyGlobal; + EXTRA_DATA_INPUT: WebAssemblyGlobal; + SIGNATURE_INPUT: WebAssemblyGlobal; + initializeContext: () => void; + isPoint: (p: number) => number; + pointAdd: (pA: number, pB: number, outputlen: number) => number; + pointAddScalar: (p: number, outputlen: number) => number; + pointCompress: (p: number, outputlen: number) => number; + pointFromScalar: (outputlen: number) => number; + xOnlyPointFromScalar: () => number; + xOnlyPointFromPoint: (inputLen: number) => number; + xOnlyPointAddTweak: () => 1 | 0 | -1; + xOnlyPointAddTweakCheck: (parity: number) => number; + pointMultiply: (p: number, outputlen: number) => number; + privateAdd: () => number; + privateSub: () => number; + privateNegate: () => void; + sign: (e: number) => void; + signRecoverable: (e: number) => 0 | 1 | 2 | 3; + signSchnorr: (e: number) => void; + verify: (Q: number, strict: number) => number; + verifySchnorr: () => number; + recover: (outputlen: number, recoveryId: RecoveryIdType) => number; +} +declare const _default: Secp256k1WASM; +export default _default; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.js b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.js new file mode 100644 index 0000000..30bec94 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_loader.js @@ -0,0 +1,12 @@ +import { readFileSync } from "fs"; +import { path } from "./wasm_path.js"; +import * as rand from "./rand.js"; +import * as validate_error from "./validate_error.js"; +const binary = readFileSync(path("secp256k1.wasm")); +const imports = { + "./rand.js": rand, + "./validate_error.js": validate_error, +}; +const mod = new WebAssembly.Module(binary); +const instance = new WebAssembly.Instance(mod, imports); +export default instance.exports; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.d.ts b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.d.ts new file mode 100644 index 0000000..d5598f6 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.d.ts @@ -0,0 +1 @@ +export declare function path(wasmFilename: string): string; diff --git a/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.js b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.js new file mode 100644 index 0000000..d45b843 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/lib/wasm_path.js @@ -0,0 +1,5 @@ +import { URL, fileURLToPath } from "url"; +export function path(wasmFilename) { + const url = new URL(wasmFilename, import.meta.url); + return fileURLToPath(url); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/LICENSE b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/LICENSE new file mode 100644 index 0000000..46c1a64 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Jonathan Underwood + +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. diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/README.md b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/README.md new file mode 100644 index 0000000..867ffcd --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/README.md @@ -0,0 +1,23 @@ +# Uint8Array Tools + +This library is licensed under MIT. + +## Usage + +Note: `fromHex` and `compare` mimic the `Buffer.from('ff', 'hex')` and +`buf1.compare(buf2)` API. Their behavior should be the same in the browser +as well as in Node. + +```js +import * as uint8arraytools from 'uint8array-tools'; +uint8arraytools.fromHex('ff'); +// Uint8Array(1) [ 255 ] +uint8arraytools.toHex(Uint8Array.from([0xff])); +// 'ff' +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0x01])); +// 1 +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0xff])); +// 0 +uint8arraytools.compare(Uint8Array.from([0x01]), Uint8Array.from([0xff])); +// -1 +``` \ No newline at end of file diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/package.json b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/package.json new file mode 100644 index 0000000..241b102 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/package.json @@ -0,0 +1,64 @@ +{ + "name": "uint8array-tools", + "version": "0.0.7", + "description": "A library for dealing with Uint8Arrays.", + "homepage": "https://github.com/bitcoinjs/uint8array-tools#readme", + "bugs": { + "url": "https://github.com/bitcoinjs/uint8array-tools/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/uint8array-tools.git" + }, + "main": "./src/cjs/index.cjs", + "exports": { + "node": { + "module": "./src/mjs/index.js", + "require": "./src/cjs/index.cjs", + "import": "./src/mjs/index.js" + }, + "browser": "./src/mjs/browser.js", + "default": "./src/mjs/browser.js" + }, + "types": "src/cjs/index.d.ts", + "type": "module", + "scripts": { + "build": "npm run clean && npm run build-ts && npm run convert-cjs && rm -f ./src/cjs/browser.d.ts", + "build-ts": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json", + "clean": "rm -rf ./src/* && rm -rf ./coverage && rm -f ./package-lock.json", + "convert-cjs": "for f in ./src/cjs/*.js; do mv -- \"$f\" \"${f%.js}.cjs\"; done", + "coverage": "npm run unit -- --coverage", + "eslint": "eslint ts_src/*.ts", + "format": "npm run eslint -- --fix", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "npm run eslint", + "test": "npm run unit", + "unit": "jest --config=jest.json --runInBand" + }, + "keywords": [ + "uint8array", + "hex", + "tools" + ], + "files": [ + "src" + ], + "author": "Jonathan Underwood (junderwood@bitcoinbank.co.jp)", + "license": "MIT", + "devDependencies": { + "@types/jest": "27.0.2", + "@types/node": "16.11.1", + "@typescript-eslint/eslint-plugin": "5.0.0", + "@typescript-eslint/parser": "5.0.0", + "eslint": "8.0.1", + "eslint-config-prettier": "8.3.0", + "eslint-plugin-prettier": "4.0.0", + "jest": "27.2.5", + "prettier": "2.4.1", + "ts-jest": "27.0.7", + "typescript": "4.4.4" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/browser.cjs b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/browser.cjs new file mode 100644 index 0000000..37ba40d --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/browser.cjs @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compare = exports.fromHex = exports.toHex = void 0; +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder("ascii"); +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +exports.toHex = toHex; +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +exports.fromHex = fromHex; +// Same behavior as Buffer.compare() +function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} +exports.compare = compare; diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.cjs b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.cjs new file mode 100644 index 0000000..7cdc76a --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.cjs @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compare = exports.fromHex = exports.toHex = void 0; +function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +exports.toHex = toHex; +function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +exports.fromHex = fromHex; +function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} +exports.compare = compare; diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.d.ts b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.d.ts new file mode 100644 index 0000000..da9a248 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/cjs/index.d.ts @@ -0,0 +1,4 @@ +export declare function toHex(bytes: Uint8Array): string; +export declare function fromHex(hexString: string): Uint8Array; +export declare type CompareResult = -1 | 0 | 1; +export declare function compare(v1: Uint8Array, v2: Uint8Array): CompareResult; diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/browser.js b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/browser.js new file mode 100644 index 0000000..76ba33a --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/browser.js @@ -0,0 +1,63 @@ +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder("ascii"); +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +export function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +export function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +// Same behavior as Buffer.compare() +export function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/index.js b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/index.js new file mode 100644 index 0000000..efc0382 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/node_modules/uint8array-tools/src/mjs/index.js @@ -0,0 +1,9 @@ +export function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +export function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +export function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} diff --git a/src/libMPC/node_modules/tiny-secp256k1/package.json b/src/libMPC/node_modules/tiny-secp256k1/package.json new file mode 100644 index 0000000..235f815 --- /dev/null +++ b/src/libMPC/node_modules/tiny-secp256k1/package.json @@ -0,0 +1,64 @@ +{ + "name": "tiny-secp256k1", + "version": "2.2.3", + "description": "A tiny secp256k1 JS", + "homepage": "https://github.com/bitcoinjs/tiny-secp256k1#readme", + "bugs": { + "url": "https://github.com/bitcoinjs/tiny-secp256k1/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/tiny-secp256k1.git" + }, + "license": "MIT", + "type": "module", + "main": "./lib/cjs/index.cjs", + "exports": { + ".": { + "node": { + "module": "./lib/index.js", + "require": "./lib/cjs/index.cjs", + "import": "./lib/index.js" + }, + "browser": "./lib/index.js", + "default": "./lib/index.js" + } + }, + "browser": { + "./lib/rand.js": "./lib/rand.browser.js", + "./lib/wasm_loader.js": "./lib/wasm_loader.browser.js" + }, + "types": "./lib/index.d.ts", + "files": [ + "lib" + ], + "dependencies": { + "uint8array-tools": "0.0.7" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.22.5", + "@babel/plugin-syntax-import-assertions": "^7.22.5", + "@types/node": "^14.14.35", + "@typescript-eslint/eslint-plugin": "^4.18.0", + "@typescript-eslint/parser": "^4.18.0", + "browser-run": "^10.1.0", + "buffer": "^6.0.3", + "eslint": "^7.22.0", + "eslint-config-prettier": "^8.1.0", + "eslint-plugin-prettier": "^3.3.1", + "nyc": "^15.1.0", + "path-browserify": "^1.0.1", + "prettier": "^2.2.1", + "process": "^0.11.10", + "sort-package-json": "^1.49.0", + "stream-browserify": "^3.0.0", + "tap-summary": "^4.0.0", + "tape": "^5.2.2", + "typescript": "^4.2.3", + "webpack": "^5.24.4", + "webpack-cli": "^4.5.0" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/src/libMPC/node_modules/typeforce/LICENSE b/src/libMPC/node_modules/typeforce/LICENSE new file mode 100644 index 0000000..9d62183 --- /dev/null +++ b/src/libMPC/node_modules/typeforce/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Daniel Cousens + +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. diff --git a/src/libMPC/node_modules/typeforce/README.md b/src/libMPC/node_modules/typeforce/README.md new file mode 100644 index 0000000..3905d4e --- /dev/null +++ b/src/libMPC/node_modules/typeforce/README.md @@ -0,0 +1,149 @@ +# typeforce +[![build status](https://secure.travis-ci.org/dcousens/typeforce.png)](http://travis-ci.org/dcousens/typeforce) +[![Version](https://img.shields.io/npm/v/typeforce.svg)](https://www.npmjs.org/package/typeforce) + +Another biased type checking solution for Javascript. + +Exception messages may change between patch versions, as often the patch will change some behaviour that was unexpected and naturally it results in a different error message. + +## Examples + +``` javascript +var typeforce = require('typeforce') + +var element = { prop: 'foo' } +var elementNumber = { prop: 2 } +var array = [element, element, elementNumber] + +// supported primitives 'Array', 'Boolean', 'Buffer', 'Number', 'Object', 'String' +typeforce('Array', array) + +typeforce('Number', array) +// TypeError: Expected Number, got Array + +// array types +typeforce(['Object'], array) +typeforce(typeforce.arrayOf('Object'), array) + +// supports recursive type templating +typeforce({ prop: 'Number' }, elementNumber) + +// maybe types +typeforce('?Number', 2) +typeforce('?Number', null) +typeforce(typeforce.maybe(typeforce.Number), 2) +typeforce(typeforce.maybe(typeforce.Number), null) + +// sum types +typeforce(typeforce.anyOf('String', 'Number'), 2) +typeforce(typeforce.allOf({ x: typeforce.Number }, { y: typeforce.Number }), { + x: 1, + y: 2 +}) + +// value types +typeforce(typeforce.value(3.14), 3.14) + +// custom types +function LongString (value, strict) { + if (!typeforce.String(value)) return false + if (value.length !== 32) return false + return true +} + +typeforce(LongString, '00000000000000000000000000000000') +// => OK! + +typeforce(LongString, 'not long enough') +// TypeError: Expected LongString, got String 'not long enough' +``` + +**Pro**tips: +``` javascript +// use precompiled primitives for high performance +typeforce(typeforce.Array, array) + +// or just precompile a template +var type = { + foo: 'Number', + bar: '?String' +} + +var fastType = typeforce.compile(type) +// fastType => typeforce.object({ +// foo: typeforce.Number, +// bar: typeforce.maybe(typeforce.String) +// }) + +// use strictness for recursive types to enforce whitelisting properties +typeforce({ + x: 'Number' +}, { x: 1 }, true) +// OK! + +typeforce({ + x: 'Number' +}, { x: 1, y: 2 }, true) +// TypeError: Unexpected property 'y' of type Number +``` + +**Pro**tips (extended types): +``` javascript +typeforce(typeforce.tuple('String', 'Number'), ['foo', 1]) +// OK! + +typeforce(typeforce.tuple('Number', 'Number'), ['not a number', 1]) +// TypeError: Expected property "0" of type Number, got String 'not a number' + +typeforce(typeforce.map('Number'), { + 'anyKeyIsOK': 1 +}) +// OK! + +typeforce(typeforce.map('Number', typeforce.HexN(8)), { + 'deadbeef': 1, + 'ffff0000': 2 +}) +// OK! + +function Foo () { + this.x = 2 +} + +typeforce(typeforce.quacksLike('Foo'), new Foo()) +// OK! + +// Note, any Foo will do +typeforce(typeforce.quacksLike('Foo'), new (function Foo() {})) +// OK! +``` + +**Pro**tips (no throw) +``` javascript +var typeforce = require('typeforce/nothrow') +var value = 'foobar' + +if (typeforce(typeforce.Number, value)) { + // didn't throw! + console.log(`${value} is a number`) // never happens +} else { + console.log(`Oops, ${typeforce.error.message}`) + // prints 'Oops, Expected Number, got String foobar' +} +``` + +**Pro**tips (async) +``` +var typeforce = require('typeforce/async') + +typeforce(typeforce.Number, value, function (err) { + if (err) return console.log(`Oops, ${typeforce.error.message}`) + + console.log(`${value} is a number`) // never happens +}) +``` + +**WARNING**: Be very wary of using the `quacksLike` type, as it relies on the `Foo.name` property. +If that property is mangled by a transpiler, such as `uglifyjs`, you will have a bad time. + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/typeforce/async.js b/src/libMPC/node_modules/typeforce/async.js new file mode 100644 index 0000000..f891c8d --- /dev/null +++ b/src/libMPC/node_modules/typeforce/async.js @@ -0,0 +1,17 @@ +var typeforce = require('./') + +// async wrapper +function tfAsync (type, value, strict, callback) { + // default to falsy strict if using shorthand overload + if (typeof strict === 'function') return tfAsync(type, value, false, strict) + + try { + typeforce(type, value, strict) + } catch (e) { + return callback(e) + } + + callback() +} + +module.exports = Object.assign(tfAsync, typeforce) diff --git a/src/libMPC/node_modules/typeforce/errors.js b/src/libMPC/node_modules/typeforce/errors.js new file mode 100644 index 0000000..52b4ee2 --- /dev/null +++ b/src/libMPC/node_modules/typeforce/errors.js @@ -0,0 +1,110 @@ +var native = require('./native') + +function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] +} + +function getValueTypeName (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) +} + +function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value +} + +function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t) + } +} + +function tfJSON (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' +} + +function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value) + + return 'Expected ' + tfJSON(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') +} + +function TfTypeError (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName(value) + this.message = tfErrorString(type, value, valueTypeName) + + captureStackTrace(this, TfTypeError) + this.__type = type + this.__value = value + this.__valueTypeName = valueTypeName +} + +TfTypeError.prototype = Object.create(Error.prototype) +TfTypeError.prototype.constructor = TfTypeError + +function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type ' + if (label === 'key') description = '" with key type ' + + return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName) +} + +function TfPropertyTypeError (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName(value) + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName) + } else { + this.message = 'Unexpected property "' + property + '"' + } + + captureStackTrace(this, TfTypeError) + this.__label = label + this.__property = property + this.__type = type + this.__value = value + this.__valueTypeName = valueTypeName +} + +TfPropertyTypeError.prototype = Object.create(Error.prototype) +TfPropertyTypeError.prototype.constructor = TfTypeError + +function tfCustomError (expected, actual) { + return new TfTypeError(expected, {}, actual) +} + +function tfSubError (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError) { + property = property + '.' + e.__property + + e = new TfPropertyTypeError( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ) + + // child? + } else if (e instanceof TfTypeError) { + e = new TfPropertyTypeError( + e.__type, property, label, e.__value, e.__valueTypeName + ) + } + + captureStackTrace(e) + return e +} + +module.exports = { + TfTypeError: TfTypeError, + TfPropertyTypeError: TfPropertyTypeError, + tfCustomError: tfCustomError, + tfSubError: tfSubError, + tfJSON: tfJSON, + getValueTypeName: getValueTypeName +} diff --git a/src/libMPC/node_modules/typeforce/extra.js b/src/libMPC/node_modules/typeforce/extra.js new file mode 100644 index 0000000..8e917d8 --- /dev/null +++ b/src/libMPC/node_modules/typeforce/extra.js @@ -0,0 +1,91 @@ +var NATIVE = require('./native') +var ERRORS = require('./errors') + +function _Buffer (value) { + return Buffer.isBuffer(value) +} + +function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) +} + +function _LengthN (type, length) { + var name = type.toJSON() + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name } + + return Length +} + +var _ArrayN = _LengthN.bind(null, NATIVE.Array) +var _BufferN = _LengthN.bind(null, _Buffer) +var _HexN = _LengthN.bind(null, Hex) +var _StringN = _LengthN.bind(null, NATIVE.String) + +function Range (a, b, f) { + f = f || NATIVE.Number + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + } + return _range +} + +var INT53_MAX = Math.pow(2, 53) - 1 + +function Finite (value) { + return typeof value === 'number' && isFinite(value) +} +function Int8 (value) { return ((value << 24) >> 24) === value } +function Int16 (value) { return ((value << 16) >> 16) === value } +function Int32 (value) { return (value | 0) === value } +function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value +} +function UInt8 (value) { return (value & 0xff) === value } +function UInt16 (value) { return (value & 0xffff) === value } +function UInt32 (value) { return (value >>> 0) === value } +function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value +} + +var types = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 +} + +for (var typeName in types) { + types[typeName].toJSON = function (t) { + return t + }.bind(null, typeName) +} + +module.exports = types diff --git a/src/libMPC/node_modules/typeforce/index.js b/src/libMPC/node_modules/typeforce/index.js new file mode 100644 index 0000000..45ff76c --- /dev/null +++ b/src/libMPC/node_modules/typeforce/index.js @@ -0,0 +1,260 @@ +var ERRORS = require('./errors') +var NATIVE = require('./native') + +// short-hand +var tfJSON = ERRORS.tfJSON +var TfTypeError = ERRORS.TfTypeError +var TfPropertyTypeError = ERRORS.TfPropertyTypeError +var tfSubError = ERRORS.tfSubError +var getValueTypeName = ERRORS.getValueTypeName + +var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type) + options = options || {} + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']' + if (options.length !== undefined) { + str += '{' + options.length + '}' + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}' + } + return str + } + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type) + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) } + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType) + if (propertyKeyType) propertyKeyType = compile(propertyKeyType) + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce(propertyKeyType, propertyName, strict) + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName] + typeforce(propertyType, propertyValue, strict) + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + } + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' } + } + + return _map + }, + + object: function object (uncompiled) { + var type = {} + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]) + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName + + try { + for (propertyName in type) { + var propertyType = type[propertyName] + var propertyValue = value[propertyName] + + typeforce(propertyType, propertyValue, strict) + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) } + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile) + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') } + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile) + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') } + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type } + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile) + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' } + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected } + + return _value + } +} + +// TODO: deprecate +TYPES.oneOf = TYPES.anyOf + +function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) +} + +function typeforce (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce(compile(type), value, strict) +} + +// assign types to typeforce function +for (var typeName in NATIVE) { + typeforce[typeName] = NATIVE[typeName] +} + +for (typeName in TYPES) { + typeforce[typeName] = TYPES[typeName] +} + +var EXTRA = require('./extra') +for (typeName in EXTRA) { + typeforce[typeName] = EXTRA[typeName] +} + +typeforce.compile = compile +typeforce.TfTypeError = TfTypeError +typeforce.TfPropertyTypeError = TfPropertyTypeError + +module.exports = typeforce diff --git a/src/libMPC/node_modules/typeforce/native.js b/src/libMPC/node_modules/typeforce/native.js new file mode 100644 index 0000000..9d04f55 --- /dev/null +++ b/src/libMPC/node_modules/typeforce/native.js @@ -0,0 +1,21 @@ +var types = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } +} + +// TODO: deprecate +types.Null = types.Nil + +for (var typeName in types) { + types[typeName].toJSON = function (t) { + return t + }.bind(null, typeName) +} + +module.exports = types diff --git a/src/libMPC/node_modules/typeforce/nothrow.js b/src/libMPC/node_modules/typeforce/nothrow.js new file mode 100644 index 0000000..ff5e7bf --- /dev/null +++ b/src/libMPC/node_modules/typeforce/nothrow.js @@ -0,0 +1,12 @@ +var typeforce = require('./') + +function tfNoThrow (type, value, strict) { + try { + return typeforce(type, value, strict) + } catch (e) { + tfNoThrow.error = e + return false + } +} + +module.exports = Object.assign(tfNoThrow, typeforce) diff --git a/src/libMPC/node_modules/typeforce/package.json b/src/libMPC/node_modules/typeforce/package.json new file mode 100644 index 0000000..9ce83ea --- /dev/null +++ b/src/libMPC/node_modules/typeforce/package.json @@ -0,0 +1,44 @@ +{ + "name": "typeforce", + "version": "1.18.0", + "description": "Another biased type checking solution for Javascript", + "keywords": [ + "typeforce", + "types", + "typechecking", + "type", + "exceptions", + "force" + ], + "homepage": "https://github.com/dcousens/typeforce", + "bugs": { + "url": "https://github.com/dcousens/typeforce/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "main": "index.js", + "files": [ + "async.js", + "errors.js", + "extra.js", + "index.js", + "native.js", + "nothrow.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/dcousens/typeforce.git" + }, + "scripts": { + "coverage": "nyc --check-coverage --branches 100 --functions 100 node test/*.js", + "test": "npm run standard && npm run unit", + "standard": "standard", + "unit": "node test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "nyc": "^13.1.0", + "standard": "*", + "tape": "^4.6.1" + } +} diff --git a/src/libMPC/node_modules/uint8array-tools/LICENSE b/src/libMPC/node_modules/uint8array-tools/LICENSE new file mode 100644 index 0000000..46c1a64 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Jonathan Underwood + +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. diff --git a/src/libMPC/node_modules/uint8array-tools/README.md b/src/libMPC/node_modules/uint8array-tools/README.md new file mode 100644 index 0000000..50e6b42 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/README.md @@ -0,0 +1,40 @@ +# Uint8Array Tools + +This library is licensed under MIT. + +## Usage + +Note: `fromHex` and `compare` mimic the `Buffer.from('ff', 'hex')` and +`buf1.compare(buf2)` API. Their behavior should be the same in the browser +as well as in Node. + +```js +import * as uint8arraytools from "uint8array-tools"; +uint8arraytools.fromHex("ff"); +// Uint8Array(1) [ 255 ] +uint8arraytools.toHex(Uint8Array.from([0xff])); +// 'ff' +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0x01])); +// 1 +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0xff])); +// 0 +uint8arraytools.compare(Uint8Array.from([0x01]), Uint8Array.from([0xff])); +// -1 +uint8arraytools.fromUtf8("tools"); +// Uint8Array(5) [ 116, 111, 111, 108, 115 ] +uint8arraytools.toUtf8(Uint8Array.from([116, 111, 111, 108, 115])); +// tools +uint8arraytools.concat([Uint8Array.from([1]), Uint8Array.from([2])]); +// Uint8Array(2) [ 1, 2 ] +uint8arraytools.fromBase64("dG9vbHM="); +// Uint8Array(3) [ 182, 138, 37 ] +uint8arraytools.toBase64(Uint8Array.from([116, 111, 111, 108, 115])); +// dG9vbHM= + +const uint8array = new Uint8Array(2); +uint8arraytools.writeUInt16(uint8array, 0, 0xffff - 1, "LE"); +uint8array; +// Uint8Array(2) [ 254, 255 ] +uint8arraytools.readUInt16(uint8array, 0, "LE"); +// 65534 +``` diff --git a/src/libMPC/node_modules/uint8array-tools/package.json b/src/libMPC/node_modules/uint8array-tools/package.json new file mode 100644 index 0000000..4419d82 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/package.json @@ -0,0 +1,66 @@ +{ + "name": "uint8array-tools", + "version": "0.0.9", + "description": "A library for dealing with Uint8Arrays.", + "homepage": "https://github.com/bitcoinjs/uint8array-tools#readme", + "bugs": { + "url": "https://github.com/bitcoinjs/uint8array-tools/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/uint8array-tools.git" + }, + "main": "./src/cjs/index.cjs", + "exports": { + "node": { + "module": "./src/mjs/index.js", + "require": "./src/cjs/index.cjs", + "import": "./src/mjs/index.js", + "types": "./src/cjs/index.d.ts" + }, + "browser": "./src/mjs/browser.js", + "default": "./src/mjs/browser.js", + "types": "./src/cjs/index.d.ts" + }, + "types": "src/cjs/index.d.ts", + "type": "module", + "scripts": { + "build": "npm run clean && npm run build-ts && npm run convert-cjs && rm -f ./src/cjs/browser.d.ts", + "build-ts": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json", + "clean": "rm -rf ./src/* && rm -rf ./coverage && rm -f ./package-lock.json", + "convert-cjs": "for f in ./src/cjs/*.js; do mv -- \"$f\" \"${f%.js}.cjs\"; done", + "coverage": "npm run unit -- --coverage", + "eslint": "eslint ts_src/*.ts", + "format": "npm run eslint -- --fix", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "npm run eslint", + "test": "npm run unit", + "unit": "jest --config=jest.json --runInBand" + }, + "keywords": [ + "uint8array", + "hex", + "tools" + ], + "files": [ + "src" + ], + "author": "Jonathan Underwood (junderwood@bitcoinbank.co.jp)", + "license": "MIT", + "devDependencies": { + "@types/jest": "27.0.2", + "@types/node": "16.11.1", + "@typescript-eslint/eslint-plugin": "5.0.0", + "@typescript-eslint/parser": "5.0.0", + "eslint": "8.0.1", + "eslint-config-prettier": "8.3.0", + "eslint-plugin-prettier": "4.0.0", + "jest": "27.2.5", + "prettier": "2.4.1", + "ts-jest": "27.0.7", + "typescript": "4.4.4" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/src/libMPC/node_modules/uint8array-tools/src/cjs/browser.cjs b/src/libMPC/node_modules/uint8array-tools/src/cjs/browser.cjs new file mode 100644 index 0000000..5893dbf --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/src/cjs/browser.cjs @@ -0,0 +1,429 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readInt64 = exports.readInt32 = exports.readInt16 = exports.readInt8 = exports.writeInt64 = exports.writeInt32 = exports.writeInt16 = exports.writeInt8 = exports.readUInt64 = exports.readUInt32 = exports.readUInt16 = exports.readUInt8 = exports.writeUInt64 = exports.writeUInt32 = exports.writeUInt16 = exports.writeUInt8 = exports.compare = exports.fromBase64 = exports.toBase64 = exports.fromHex = exports.toHex = exports.concat = exports.fromUtf8 = exports.toUtf8 = void 0; +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder(); +function toUtf8(bytes) { + return DECODER.decode(bytes); +} +exports.toUtf8 = toUtf8; +function fromUtf8(s) { + return ENCODER.encode(s); +} +exports.fromUtf8 = fromUtf8; +function concat(arrays) { + const totalLength = arrays.reduce((a, b) => a + b.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} +exports.concat = concat; +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +exports.toHex = toHex; +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +exports.fromHex = fromHex; +function toBase64(bytes) { + return btoa(String.fromCharCode(...bytes)); +} +exports.toBase64 = toBase64; +function fromBase64(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +exports.fromBase64 = fromBase64; +// Same behavior as Buffer.compare() +function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} +exports.compare = compare; +function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0xff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xff}. Received ${value}`); + } + buffer[offset] = value; + return offset + 1; +} +exports.writeUInt8 = writeUInt8; +function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } + return offset + 2; +} +exports.writeUInt16 = writeUInt16; +function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } + return offset + 4; +} +exports.writeUInt32 = writeUInt32; +function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } + return offset + 8; +} +exports.writeUInt64 = writeUInt64; +function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + return buffer[offset]; +} +exports.readUInt8 = readUInt8; +function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = (num << 8) + buffer[offset + 1]; + num = (num << 8) + buffer[offset]; + return num; + } + else { + let num = 0; + num = (num << 8) + buffer[offset]; + num = (num << 8) + buffer[offset + 1]; + return num; + } +} +exports.readUInt16 = readUInt16; +function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset]) >>> 0; + return num; + } + else { + let num = 0; + num = ((num << 8) + buffer[offset]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + return num; + } +} +exports.readUInt32 = readUInt32; +function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return num; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return num; + } +} +exports.readUInt64 = readUInt64; +function writeInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7f || value < -0x80) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x80} and <= ${0x7f}. Received ${value}`); + } + buffer[offset] = value; + return offset + 1; +} +exports.writeInt8 = writeInt8; +function writeInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fff || value < -0x8000) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000} and <= ${0x7fff}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } + return offset + 2; +} +exports.writeInt16 = writeInt16; +function writeInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffff || value < -0x80000000) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x80000000} and <= ${0x7fffffff}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } + return offset + 4; +} +exports.writeInt32 = writeInt32; +function writeInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffffffffffffn || value < -0x8000000000000000n) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } + return offset + 8; +} +exports.writeInt64 = writeInt64; +function readInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const val = buffer[offset]; + if (val <= 0x7f) { + return val; + } + else { + return val - 0x100; + } +} +exports.readInt8 = readInt8; +function readInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + const val = buffer[offset] + (buffer[offset + 1] << 8); + return buffer[offset + 1] <= 0x7f ? val : val - 0x10000; + } + else { + const val = (buffer[offset] << 8) + buffer[offset + 1]; + return buffer[offset] <= 0x7f ? val : val - 0x10000; + } +} +exports.readInt16 = readInt16; +function readInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + const val = buffer[offset] + + (buffer[offset + 1] << 8) + + (buffer[offset + 2] << 16) + + ((buffer[offset + 3] << 24) >>> 0); + return buffer[offset + 3] <= 0x7f ? val : val - 0x100000000; + } + else { + const val = ((buffer[offset] << 24) >>> 0) + + (buffer[offset + 1] << 16) + + (buffer[offset + 2] << 8) + + buffer[offset + 3]; + return buffer[offset] <= 0x7f ? val : val - 0x100000000; + } +} +exports.readInt32 = readInt32; +function readInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + let num = 0n; + if (littleEndian === "LE") { + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return buffer[offset + 7] <= 0x7f ? num : num - 0x10000000000000000n; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return buffer[offset] <= 0x7f ? num : num - 0x10000000000000000n; + } +} +exports.readInt64 = readInt64; diff --git a/src/libMPC/node_modules/uint8array-tools/src/cjs/index.cjs b/src/libMPC/node_modules/uint8array-tools/src/cjs/index.cjs new file mode 100644 index 0000000..ba01ad8 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/src/cjs/index.cjs @@ -0,0 +1,254 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readInt64 = exports.readInt32 = exports.readInt16 = exports.readInt8 = exports.writeInt64 = exports.writeInt32 = exports.writeInt16 = exports.writeInt8 = exports.readUInt64 = exports.readUInt32 = exports.readUInt16 = exports.readUInt8 = exports.writeUInt64 = exports.writeUInt32 = exports.writeUInt16 = exports.writeUInt8 = exports.compare = exports.fromBase64 = exports.toBase64 = exports.fromHex = exports.toHex = exports.concat = exports.fromUtf8 = exports.toUtf8 = void 0; +function toUtf8(bytes) { + return Buffer.from(bytes || []).toString(); +} +exports.toUtf8 = toUtf8; +function fromUtf8(s) { + return Uint8Array.from(Buffer.from(s || "", "utf8")); +} +exports.fromUtf8 = fromUtf8; +function concat(arrays) { + return Uint8Array.from(Buffer.concat(arrays)); +} +exports.concat = concat; +function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +exports.toHex = toHex; +function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +exports.fromHex = fromHex; +function toBase64(bytes) { + return Buffer.from(bytes).toString("base64"); +} +exports.toBase64 = toBase64; +function fromBase64(base64) { + return Uint8Array.from(Buffer.from(base64 || "", "base64")); +} +exports.fromBase64 = fromBase64; +function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} +exports.compare = compare; +function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeUInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); + return offset + 1; +} +exports.writeUInt8 = writeUInt8; +function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeUInt16LE(value, 0); + } + else { + buf.writeUInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 2; +} +exports.writeUInt16 = writeUInt16; +function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeUInt32LE(value, 0); + } + else { + buf.writeUInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 4; +} +exports.writeUInt32 = writeUInt32; +function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buf.writeBigUInt64LE(value, 0); + } + else { + buf.writeBigUInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 8; +} +exports.writeUInt64 = writeUInt64; +function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readUInt8(offset); +} +exports.readUInt8 = readUInt8; +function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt16LE(offset); + } + else { + return buf.readUInt16BE(offset); + } +} +exports.readUInt16 = readUInt16; +function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt32LE(offset); + } + else { + return buf.readUInt32BE(offset); + } +} +exports.readUInt32 = readUInt32; +function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readBigUInt64LE(offset); + } + else { + return buf.readBigUInt64BE(offset); + } +} +exports.readUInt64 = readUInt64; +function writeInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); + return offset + 1; +} +exports.writeInt8 = writeInt8; +function writeInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeInt16LE(value, 0); + } + else { + buf.writeInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 2; +} +exports.writeInt16 = writeInt16; +function writeInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeInt32LE(value, 0); + } + else { + buf.writeInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 4; +} +exports.writeInt32 = writeInt32; +function writeInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffffffffffffn || value < -0x8000000000000000n) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (littleEndian === "LE") { + buf.writeBigInt64LE(value, 0); + } + else { + buf.writeBigInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 8; +} +exports.writeInt64 = writeInt64; +function readInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readInt8(offset); +} +exports.readInt8 = readInt8; +function readInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readInt16LE(offset); + } + else { + return Buffer.from(buffer).readInt16BE(offset); + } +} +exports.readInt16 = readInt16; +function readInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readInt32LE(offset); + } + else { + return Buffer.from(buffer).readInt32BE(offset); + } +} +exports.readInt32 = readInt32; +function readInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readBigInt64LE(offset); + } + else { + return Buffer.from(buffer).readBigInt64BE(offset); + } +} +exports.readInt64 = readInt64; diff --git a/src/libMPC/node_modules/uint8array-tools/src/cjs/index.d.ts b/src/libMPC/node_modules/uint8array-tools/src/cjs/index.d.ts new file mode 100644 index 0000000..14ae044 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/src/cjs/index.d.ts @@ -0,0 +1,26 @@ +export declare function toUtf8(bytes: Uint8Array): string; +export declare function fromUtf8(s: string): Uint8Array; +export declare function concat(arrays: Uint8Array[]): Uint8Array; +export declare function toHex(bytes: Uint8Array): string; +export declare function fromHex(hexString: string): Uint8Array; +export declare function toBase64(bytes: Uint8Array): string; +export declare function fromBase64(base64: string): Uint8Array; +export declare type CompareResult = -1 | 0 | 1; +export declare function compare(v1: Uint8Array, v2: Uint8Array): CompareResult; +export declare type endian = "LE" | "BE" | "le" | "be"; +export declare function writeUInt8(buffer: Uint8Array, offset: number, value: number): number; +export declare function writeUInt16(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): number; +export declare function writeUInt32(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): number; +export declare function writeUInt64(buffer: Uint8Array, offset: number, value: bigint, littleEndian: endian): number; +export declare function readUInt8(buffer: Uint8Array, offset: number): number; +export declare function readUInt16(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readUInt32(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readUInt64(buffer: Uint8Array, offset: number, littleEndian: endian): bigint; +export declare function writeInt8(buffer: Uint8Array, offset: number, value: number): number; +export declare function writeInt16(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): number; +export declare function writeInt32(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): number; +export declare function writeInt64(buffer: Uint8Array, offset: number, value: bigint, littleEndian: endian): number; +export declare function readInt8(buffer: Uint8Array, offset: number): number; +export declare function readInt16(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readInt32(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readInt64(buffer: Uint8Array, offset: number, littleEndian: endian): bigint; diff --git a/src/libMPC/node_modules/uint8array-tools/src/mjs/browser.js b/src/libMPC/node_modules/uint8array-tools/src/mjs/browser.js new file mode 100644 index 0000000..7d815c1 --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/src/mjs/browser.js @@ -0,0 +1,402 @@ +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder(); +export function toUtf8(bytes) { + return DECODER.decode(bytes); +} +export function fromUtf8(s) { + return ENCODER.encode(s); +} +export function concat(arrays) { + const totalLength = arrays.reduce((a, b) => a + b.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +export function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +export function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +export function toBase64(bytes) { + return btoa(String.fromCharCode(...bytes)); +} +export function fromBase64(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +// Same behavior as Buffer.compare() +export function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} +export function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0xff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xff}. Received ${value}`); + } + buffer[offset] = value; + return offset + 1; +} +export function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } + return offset + 2; +} +export function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } + return offset + 4; +} +export function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } + return offset + 8; +} +export function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + return buffer[offset]; +} +export function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = (num << 8) + buffer[offset + 1]; + num = (num << 8) + buffer[offset]; + return num; + } + else { + let num = 0; + num = (num << 8) + buffer[offset]; + num = (num << 8) + buffer[offset + 1]; + return num; + } +} +export function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset]) >>> 0; + return num; + } + else { + let num = 0; + num = ((num << 8) + buffer[offset]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + return num; + } +} +export function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return num; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return num; + } +} +export function writeInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7f || value < -0x80) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x80} and <= ${0x7f}. Received ${value}`); + } + buffer[offset] = value; + return offset + 1; +} +export function writeInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fff || value < -0x8000) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000} and <= ${0x7fff}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } + return offset + 2; +} +export function writeInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffff || value < -0x80000000) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x80000000} and <= ${0x7fffffff}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } + return offset + 4; +} +export function writeInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffffffffffffn || value < -0x8000000000000000n) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } + return offset + 8; +} +export function readInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const val = buffer[offset]; + if (val <= 0x7f) { + return val; + } + else { + return val - 0x100; + } +} +export function readInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + const val = buffer[offset] + (buffer[offset + 1] << 8); + return buffer[offset + 1] <= 0x7f ? val : val - 0x10000; + } + else { + const val = (buffer[offset] << 8) + buffer[offset + 1]; + return buffer[offset] <= 0x7f ? val : val - 0x10000; + } +} +export function readInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + const val = buffer[offset] + + (buffer[offset + 1] << 8) + + (buffer[offset + 2] << 16) + + ((buffer[offset + 3] << 24) >>> 0); + return buffer[offset + 3] <= 0x7f ? val : val - 0x100000000; + } + else { + const val = ((buffer[offset] << 24) >>> 0) + + (buffer[offset + 1] << 16) + + (buffer[offset + 2] << 8) + + buffer[offset + 3]; + return buffer[offset] <= 0x7f ? val : val - 0x100000000; + } +} +export function readInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + let num = 0n; + if (littleEndian === "LE") { + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return buffer[offset + 7] <= 0x7f ? num : num - 0x10000000000000000n; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return buffer[offset] <= 0x7f ? num : num - 0x10000000000000000n; + } +} diff --git a/src/libMPC/node_modules/uint8array-tools/src/mjs/index.js b/src/libMPC/node_modules/uint8array-tools/src/mjs/index.js new file mode 100644 index 0000000..3e3a85b --- /dev/null +++ b/src/libMPC/node_modules/uint8array-tools/src/mjs/index.js @@ -0,0 +1,227 @@ +export function toUtf8(bytes) { + return Buffer.from(bytes || []).toString(); +} +export function fromUtf8(s) { + return Uint8Array.from(Buffer.from(s || "", "utf8")); +} +export function concat(arrays) { + return Uint8Array.from(Buffer.concat(arrays)); +} +export function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +export function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +export function toBase64(bytes) { + return Buffer.from(bytes).toString("base64"); +} +export function fromBase64(base64) { + return Uint8Array.from(Buffer.from(base64 || "", "base64")); +} +export function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} +export function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeUInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); + return offset + 1; +} +export function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeUInt16LE(value, 0); + } + else { + buf.writeUInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 2; +} +export function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeUInt32LE(value, 0); + } + else { + buf.writeUInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 4; +} +export function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buf.writeBigUInt64LE(value, 0); + } + else { + buf.writeBigUInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 8; +} +export function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readUInt8(offset); +} +export function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt16LE(offset); + } + else { + return buf.readUInt16BE(offset); + } +} +export function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt32LE(offset); + } + else { + return buf.readUInt32BE(offset); + } +} +export function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readBigUInt64LE(offset); + } + else { + return buf.readBigUInt64BE(offset); + } +} +export function writeInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); + return offset + 1; +} +export function writeInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeInt16LE(value, 0); + } + else { + buf.writeInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 2; +} +export function writeInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeInt32LE(value, 0); + } + else { + buf.writeInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 4; +} +export function writeInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0x7fffffffffffffffn || value < -0x8000000000000000n) { + throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${value}`); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (littleEndian === "LE") { + buf.writeBigInt64LE(value, 0); + } + else { + buf.writeBigInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); + return offset + 8; +} +export function readInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readInt8(offset); +} +export function readInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readInt16LE(offset); + } + else { + return Buffer.from(buffer).readInt16BE(offset); + } +} +export function readInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readInt32LE(offset); + } + else { + return Buffer.from(buffer).readInt32BE(offset); + } +} +export function readInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + return Buffer.from(buffer).readBigInt64LE(offset); + } + else { + return Buffer.from(buffer).readBigInt64BE(offset); + } +} diff --git a/src/libMPC/node_modules/util-deprecate/History.md b/src/libMPC/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/src/libMPC/node_modules/util-deprecate/LICENSE b/src/libMPC/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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. diff --git a/src/libMPC/node_modules/util-deprecate/README.md b/src/libMPC/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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. diff --git a/src/libMPC/node_modules/util-deprecate/browser.js b/src/libMPC/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/src/libMPC/node_modules/util-deprecate/node.js b/src/libMPC/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/src/libMPC/node_modules/util-deprecate/package.json b/src/libMPC/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/src/libMPC/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/src/libMPC/node_modules/valibot/LICENSE.md b/src/libMPC/node_modules/valibot/LICENSE.md new file mode 100644 index 0000000..3a695a6 --- /dev/null +++ b/src/libMPC/node_modules/valibot/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Fabian Hiller + +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. diff --git a/src/libMPC/node_modules/valibot/README.md b/src/libMPC/node_modules/valibot/README.md new file mode 100644 index 0000000..7d9221c --- /dev/null +++ b/src/libMPC/node_modules/valibot/README.md @@ -0,0 +1,79 @@ +![Valibot Logo](https://github.com/fabian-hiller/valibot/blob/main/valibot.jpg?raw=true) + +# Valibot + +[![License: MIT][license-image]][license-url] +[![CI][ci-image]][ci-url] +[![NPM version][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] +[![Discord][discord-image]][discord-url] + +Hello, I am Valibot and I would like to help you validate data easily using a schema. No matter if it is incoming data on a server, a form or even configuration files. I have no dependencies and can run in any JavaScript environment. + +> I highly recommend you read the [announcement post](https://www.builder.io/blog/introducing-valibot), and if you are a nerd like me, the [bachelor's thesis](https://valibot.dev/thesis.pdf) I am based on. + +## Highlights + +- Fully type safe with static type inference +- Small bundle size starting at less than 600 bytes +- Validate everything from strings to complex objects +- Open source and fully tested with 100 % coverage +- Many transformation and validation actions included +- Well structured source code without dependencies +- Minimal, readable and well thought out API + +## Example + +First you create a schema that describes a structured data set. A schema can be compared to a type definition in TypeScript. The big difference is that TypeScript types are "not executed" and are more or less a DX feature. A schema on the other hand, apart from the inferred type definition, can also be executed at runtime to guarantee type safety of unknown data. + + +```ts +import * as v from 'valibot'; // 1.2 kB + +// Create login schema with email and password +const LoginSchema = v.object({ + email: v.pipe(v.string(), v.email()), + password: v.pipe(v.string(), v.minLength(8)), +}); + +// Infer output TypeScript type of login schema +type LoginData = v.InferOutput; // { email: string; password: string } + +// Throws error for `email` and `password` +v.parse(LoginSchema, { email: '', password: '' }); + +// Returns data as { email: string; password: string } +v.parse(LoginSchema, { email: 'jane@example.com', password: '12345678' }); +``` + +Apart from `parse` I also offer a non-exception-based API with `safeParse` and a type guard function with `is`. You can read more about it [here](https://valibot.dev/guides/parse-data/). + +## Comparison + +Instead of relying on a few large functions with many methods, my API design and source code is based on many small and independent functions, each with just a single task. This modular design has several advantages. + +For example, this allows a bundler to use the import statements to remove code that is not needed. This way, only the code that is actually used gets into your production build. This can reduce the bundle size by up to 95 % compared to [Zod](https://zod.dev/). + +In addition, it allows you to easily extend my functionality with external code and makes my source code more robust and secure because the functionality of the individual functions can be tested much more easily through unit tests. + +## Credits + +My friend [Fabian](https://twitter.com/FabianHiller) created me as part of his bachelor thesis at [Stuttgart Media University](https://www.hdm-stuttgart.de/en/), supervised by Walter Kriha, [Miško Hevery](https://twitter.com/mhevery) and [Ryan Carniato](https://twitter.com/RyanCarniato). My role models also include [Colin McDonnell](https://twitter.com/colinhacks), who had a big influence on my API design with [Zod](https://zod.dev/). + +## Feedback + +Find a bug or have an idea how to improve my code? Please fill out an [issue](https://github.com/fabian-hiller/valibot/issues/new). Together we can make the library even better! + +## License + +I am completely free and licensed under the [MIT license](https://github.com/fabian-hiller/valibot/blob/main/LICENSE.md). But if you like, you can feed me with a star on [GitHub](https://github.com/fabian-hiller/valibot). + +[license-image]: https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square +[license-url]: https://opensource.org/licenses/MIT +[ci-image]: https://img.shields.io/github/actions/workflow/status/fabian-hiller/valibot/ci.yml?branch=main&logo=github&style=flat-square +[ci-url]: https://github.com/fabian-hiller/valibot/actions/workflows/ci.yml +[npm-image]: https://img.shields.io/npm/v/valibot.svg?style=flat-square +[npm-url]: https://npmjs.org/package/valibot +[downloads-image]: https://img.shields.io/npm/dm/valibot.svg?style=flat-square +[discord-image]: https://img.shields.io/discord/1252985447273992222?label=Discord&style=flat-square +[discord-url]: https://discord.gg/tkMjQACf2P diff --git a/src/libMPC/node_modules/valibot/dist/index.cjs b/src/libMPC/node_modules/valibot/dist/index.cjs new file mode 100644 index 0000000..1f16a4a --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.cjs @@ -0,0 +1,5958 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + BASE64_REGEX: () => BASE64_REGEX, + BIC_REGEX: () => BIC_REGEX, + CUID2_REGEX: () => CUID2_REGEX, + DECIMAL_REGEX: () => DECIMAL_REGEX, + EMAIL_REGEX: () => EMAIL_REGEX, + EMOJI_REGEX: () => EMOJI_REGEX, + HEXADECIMAL_REGEX: () => HEXADECIMAL_REGEX, + HEX_COLOR_REGEX: () => HEX_COLOR_REGEX, + IMEI_REGEX: () => IMEI_REGEX, + IPV4_REGEX: () => IPV4_REGEX, + IPV6_REGEX: () => IPV6_REGEX, + IP_REGEX: () => IP_REGEX, + ISO_DATE_REGEX: () => ISO_DATE_REGEX, + ISO_DATE_TIME_REGEX: () => ISO_DATE_TIME_REGEX, + ISO_TIMESTAMP_REGEX: () => ISO_TIMESTAMP_REGEX, + ISO_TIME_REGEX: () => ISO_TIME_REGEX, + ISO_TIME_SECOND_REGEX: () => ISO_TIME_SECOND_REGEX, + ISO_WEEK_REGEX: () => ISO_WEEK_REGEX, + MAC48_REGEX: () => MAC48_REGEX, + MAC64_REGEX: () => MAC64_REGEX, + MAC_REGEX: () => MAC_REGEX, + OCTAL_REGEX: () => OCTAL_REGEX, + ULID_REGEX: () => ULID_REGEX, + UUID_REGEX: () => UUID_REGEX, + ValiError: () => ValiError, + _addIssue: () => _addIssue, + _isLuhnAlgo: () => _isLuhnAlgo, + _isValidObjectKey: () => _isValidObjectKey, + _joinExpects: () => _joinExpects, + _stringify: () => _stringify, + any: () => any, + array: () => array, + arrayAsync: () => arrayAsync, + awaitAsync: () => awaitAsync, + base64: () => base64, + bic: () => bic, + bigint: () => bigint, + blob: () => blob, + boolean: () => boolean, + brand: () => brand, + bytes: () => bytes, + check: () => check, + checkAsync: () => checkAsync, + checkItems: () => checkItems, + config: () => config, + creditCard: () => creditCard, + cuid2: () => cuid2, + custom: () => custom, + customAsync: () => customAsync, + date: () => date, + decimal: () => decimal, + deleteGlobalConfig: () => deleteGlobalConfig, + deleteGlobalMessage: () => deleteGlobalMessage, + deleteSchemaMessage: () => deleteSchemaMessage, + deleteSpecificMessage: () => deleteSpecificMessage, + description: () => description, + email: () => email, + emoji: () => emoji, + empty: () => empty, + endsWith: () => endsWith, + entriesFromList: () => entriesFromList, + enum: () => enum_, + enum_: () => enum_, + everyItem: () => everyItem, + excludes: () => excludes, + fallback: () => fallback, + fallbackAsync: () => fallbackAsync, + file: () => file, + filterItems: () => filterItems, + findItem: () => findItem, + finite: () => finite, + flatten: () => flatten, + forward: () => forward, + forwardAsync: () => forwardAsync, + function: () => function_, + function_: () => function_, + getDefault: () => getDefault, + getDefaults: () => getDefaults, + getDefaultsAsync: () => getDefaultsAsync, + getDotPath: () => getDotPath, + getFallback: () => getFallback, + getFallbacks: () => getFallbacks, + getFallbacksAsync: () => getFallbacksAsync, + getGlobalConfig: () => getGlobalConfig, + getGlobalMessage: () => getGlobalMessage, + getSchemaMessage: () => getSchemaMessage, + getSpecificMessage: () => getSpecificMessage, + hash: () => hash, + hexColor: () => hexColor, + hexadecimal: () => hexadecimal, + imei: () => imei, + includes: () => includes, + instance: () => instance, + integer: () => integer, + intersect: () => intersect, + intersectAsync: () => intersectAsync, + ip: () => ip, + ipv4: () => ipv4, + ipv6: () => ipv6, + is: () => is, + isOfKind: () => isOfKind, + isOfType: () => isOfType, + isValiError: () => isValiError, + isoDate: () => isoDate, + isoDateTime: () => isoDateTime, + isoTime: () => isoTime, + isoTimeSecond: () => isoTimeSecond, + isoTimestamp: () => isoTimestamp, + isoWeek: () => isoWeek, + keyof: () => keyof, + lazy: () => lazy, + lazyAsync: () => lazyAsync, + length: () => length, + literal: () => literal, + looseObject: () => looseObject, + looseObjectAsync: () => looseObjectAsync, + looseTuple: () => looseTuple, + looseTupleAsync: () => looseTupleAsync, + mac: () => mac, + mac48: () => mac48, + mac64: () => mac64, + map: () => map, + mapAsync: () => mapAsync, + mapItems: () => mapItems, + maxBytes: () => maxBytes, + maxLength: () => maxLength, + maxSize: () => maxSize, + maxValue: () => maxValue, + mimeType: () => mimeType, + minBytes: () => minBytes, + minLength: () => minLength, + minSize: () => minSize, + minValue: () => minValue, + multipleOf: () => multipleOf, + nan: () => nan, + never: () => never, + nonEmpty: () => nonEmpty, + nonNullable: () => nonNullable, + nonNullableAsync: () => nonNullableAsync, + nonNullish: () => nonNullish, + nonNullishAsync: () => nonNullishAsync, + nonOptional: () => nonOptional, + nonOptionalAsync: () => nonOptionalAsync, + normalize: () => normalize, + notBytes: () => notBytes, + notLength: () => notLength, + notSize: () => notSize, + notValue: () => notValue, + null: () => null_, + null_: () => null_, + nullable: () => nullable, + nullableAsync: () => nullableAsync, + nullish: () => nullish, + nullishAsync: () => nullishAsync, + number: () => number, + object: () => object, + objectAsync: () => objectAsync, + objectWithRest: () => objectWithRest, + objectWithRestAsync: () => objectWithRestAsync, + octal: () => octal, + omit: () => omit, + optional: () => optional, + optionalAsync: () => optionalAsync, + parse: () => parse, + parseAsync: () => parseAsync, + parser: () => parser, + parserAsync: () => parserAsync, + partial: () => partial, + partialAsync: () => partialAsync, + partialCheck: () => partialCheck, + partialCheckAsync: () => partialCheckAsync, + pick: () => pick, + picklist: () => picklist, + pipe: () => pipe, + pipeAsync: () => pipeAsync, + promise: () => promise, + rawCheck: () => rawCheck, + rawCheckAsync: () => rawCheckAsync, + rawTransform: () => rawTransform, + rawTransformAsync: () => rawTransformAsync, + readonly: () => readonly, + record: () => record, + recordAsync: () => recordAsync, + reduceItems: () => reduceItems, + regex: () => regex, + required: () => required, + requiredAsync: () => requiredAsync, + safeInteger: () => safeInteger, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + safeParser: () => safeParser, + safeParserAsync: () => safeParserAsync, + set: () => set, + setAsync: () => setAsync, + setGlobalConfig: () => setGlobalConfig, + setGlobalMessage: () => setGlobalMessage, + setSchemaMessage: () => setSchemaMessage, + setSpecificMessage: () => setSpecificMessage, + size: () => size, + someItem: () => someItem, + sortItems: () => sortItems, + startsWith: () => startsWith, + strictObject: () => strictObject, + strictObjectAsync: () => strictObjectAsync, + strictTuple: () => strictTuple, + strictTupleAsync: () => strictTupleAsync, + string: () => string, + symbol: () => symbol, + toLowerCase: () => toLowerCase, + toMaxValue: () => toMaxValue, + toMinValue: () => toMinValue, + toUpperCase: () => toUpperCase, + transform: () => transform, + transformAsync: () => transformAsync, + trim: () => trim, + trimEnd: () => trimEnd, + trimStart: () => trimStart, + tuple: () => tuple, + tupleAsync: () => tupleAsync, + tupleWithRest: () => tupleWithRest, + tupleWithRestAsync: () => tupleWithRestAsync, + ulid: () => ulid, + undefined: () => undefined_, + undefined_: () => undefined_, + union: () => union, + unionAsync: () => unionAsync, + unknown: () => unknown, + unwrap: () => unwrap, + url: () => url, + uuid: () => uuid, + value: () => value, + variant: () => variant, + variantAsync: () => variantAsync, + void: () => void_, + void_: () => void_ +}); +module.exports = __toCommonJS(src_exports); + +// src/actions/await/awaitAsync.ts +function awaitAsync() { + return { + kind: "transformation", + type: "await", + reference: awaitAsync, + async: true, + async _run(dataset) { + dataset.value = await dataset.value; + return dataset; + } + }; +} + +// src/regex.ts +var BASE64_REGEX = /^(?:[\da-z+/]{4})*(?:[\da-z+/]{2}==|[\da-z+/]{3}=)?$/iu; +var BIC_REGEX = /^[A-Z]{6}(?!00)[\dA-Z]{2}(?:[\dA-Z]{3})?$/u; +var CUID2_REGEX = /^[a-z][\da-z]*$/u; +var DECIMAL_REGEX = /^\d+$/u; +var EMAIL_REGEX = /^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu; +var EMOJI_REGEX = ( + // eslint-disable-next-line redos-detector/no-unsafe-regex, regexp/no-dupe-disjunctions -- false positives + /^(?:[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}))*)+$/u +); +var HEXADECIMAL_REGEX = /^(?:0[hx])?[\da-f]+$/iu; +var HEX_COLOR_REGEX = /^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/iu; +var IMEI_REGEX = /^\d{15}$|^\d{2}-\d{6}-\d{6}-\d$/u; +var IPV4_REGEX = ( + // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive + /^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$/u +); +var IPV6_REGEX = /^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu; +var IP_REGEX = /^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$|^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu; +var ISO_DATE_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])$/u; +var ISO_DATE_TIME_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])T(?:0\d|1\d|2[0-3]):[0-5]\d$/u; +var ISO_TIME_REGEX = /^(?:0\d|1\d|2[0-3]):[0-5]\d$/u; +var ISO_TIME_SECOND_REGEX = /^(?:0\d|1\d|2[0-3])(?::[0-5]\d){2}$/u; +var ISO_TIMESTAMP_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])T(?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z|[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u; +var ISO_WEEK_REGEX = /^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/u; +var MAC48_REGEX = /^(?:[\da-f]{2}:){5}[\da-f]{2}$|^(?:[\da-f]{2}-){5}[\da-f]{2}$|^(?:[\da-f]{4}\.){2}[\da-f]{4}$/iu; +var MAC64_REGEX = /^(?:[\da-f]{2}:){7}[\da-f]{2}$|^(?:[\da-f]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu; +var MAC_REGEX = /^(?:[\da-f]{2}:){5}[\da-f]{2}$|^(?:[\da-f]{2}-){5}[\da-f]{2}$|^(?:[\da-f]{4}\.){2}[\da-f]{4}$|^(?:[\da-f]{2}:){7}[\da-f]{2}$|^(?:[\da-f]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu; +var OCTAL_REGEX = /^(?:0o)?[0-7]+$/iu; +var ULID_REGEX = /^[\da-hjkmnp-tv-z]{26}$/iu; +var UUID_REGEX = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu; + +// src/storages/globalConfig/globalConfig.ts +var store; +function setGlobalConfig(config2) { + store = { ...store, ...config2 }; +} +function getGlobalConfig(config2) { + return { + lang: config2?.lang ?? store?.lang, + message: config2?.message, + abortEarly: config2?.abortEarly ?? store?.abortEarly, + abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly + }; +} +function deleteGlobalConfig() { + store = void 0; +} + +// src/storages/globalMessage/globalMessage.ts +var store2; +function setGlobalMessage(message, lang) { + if (!store2) store2 = /* @__PURE__ */ new Map(); + store2.set(lang, message); +} +function getGlobalMessage(lang) { + return store2?.get(lang); +} +function deleteGlobalMessage(lang) { + store2?.delete(lang); +} + +// src/storages/schemaMessage/schemaMessage.ts +var store3; +function setSchemaMessage(message, lang) { + if (!store3) store3 = /* @__PURE__ */ new Map(); + store3.set(lang, message); +} +function getSchemaMessage(lang) { + return store3?.get(lang); +} +function deleteSchemaMessage(lang) { + store3?.delete(lang); +} + +// src/storages/specificMessage/specificMessage.ts +var store4; +function setSpecificMessage(reference, message, lang) { + if (!store4) store4 = /* @__PURE__ */ new Map(); + if (!store4.get(reference)) store4.set(reference, /* @__PURE__ */ new Map()); + store4.get(reference).set(lang, message); +} +function getSpecificMessage(reference, lang) { + return store4?.get(reference)?.get(lang); +} +function deleteSpecificMessage(reference, lang) { + store4?.get(reference)?.delete(lang); +} + +// src/utils/_stringify/_stringify.ts +function _stringify(input) { + const type = typeof input; + if (type === "string") { + return `"${input}"`; + } + if (type === "number" || type === "bigint" || type === "boolean") { + return `${input}`; + } + if (type === "object" || type === "function") { + return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null"; + } + return type; +} + +// src/utils/_addIssue/_addIssue.ts +function _addIssue(context, label, dataset, config2, other) { + const input = other && "input" in other ? other.input : dataset.value; + const expected = other?.expected ?? context.expects ?? null; + const received = other?.received ?? _stringify(input); + const issue = { + kind: context.kind, + type: context.type, + input, + expected, + received, + message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`, + // @ts-expect-error + requirement: context.requirement, + path: other?.path, + issues: other?.issues, + lang: config2.lang, + abortEarly: config2.abortEarly, + abortPipeEarly: config2.abortPipeEarly + }; + const isSchema = context.kind === "schema"; + const message = other?.message ?? // @ts-expect-error + context.message ?? getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? getSchemaMessage(issue.lang) : null) ?? config2.message ?? getGlobalMessage(issue.lang); + if (message) { + issue.message = typeof message === "function" ? message(issue) : message; + } + if (isSchema) { + dataset.typed = false; + } + if (dataset.issues) { + dataset.issues.push(issue); + } else { + dataset.issues = [issue]; + } +} + +// src/utils/_isLuhnAlgo/_isLuhnAlgo.ts +var NON_DIGIT_REGEX = /\D/gu; +function _isLuhnAlgo(input) { + const number2 = input.replace(NON_DIGIT_REGEX, ""); + let length2 = number2.length; + let bit = 1; + let sum = 0; + while (length2) { + const value2 = +number2[--length2]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value2] : value2; + } + return sum % 10 === 0; +} + +// src/utils/_isValidObjectKey/_isValidObjectKey.ts +function _isValidObjectKey(object2, key) { + return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor"; +} + +// src/utils/_joinExpects/_joinExpects.ts +function _joinExpects(values, separator) { + const list = [...new Set(values)]; + if (list.length > 1) { + return `(${list.join(` ${separator} `)})`; + } + return list[0] ?? "never"; +} + +// src/utils/entriesFromList/entriesFromList.ts +function entriesFromList(list, schema) { + const entries = {}; + for (const key of list) { + entries[key] = schema; + } + return entries; +} + +// src/utils/getDotPath/getDotPath.ts +function getDotPath(issue) { + if (issue.path) { + let key = ""; + for (const item of issue.path) { + if (typeof item.key === "string" || typeof item.key === "number") { + if (key) { + key += `.${item.key}`; + } else { + key += item.key; + } + } else { + return null; + } + } + return key; + } + return null; +} + +// src/utils/isOfKind/isOfKind.ts +function isOfKind(kind, object2) { + return object2.kind === kind; +} + +// src/utils/isOfType/isOfType.ts +function isOfType(type, object2) { + return object2.type === type; +} + +// src/utils/isValiError/isValiError.ts +function isValiError(error) { + return error instanceof ValiError; +} + +// src/utils/ValiError/ValiError.ts +var ValiError = class extends Error { + /** + * The error issues. + */ + issues; + /** + * Creates a Valibot error with useful information. + * + * @param issues The error issues. + */ + constructor(issues) { + super(issues[0].message); + this.name = "ValiError"; + this.issues = issues; + } +}; + +// src/actions/base64/base64.ts +function base64(message) { + return { + kind: "validation", + type: "base64", + reference: base64, + async: false, + expects: null, + requirement: BASE64_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "Base64", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/bic/bic.ts +function bic(message) { + return { + kind: "validation", + type: "bic", + reference: bic, + async: false, + expects: null, + requirement: BIC_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "BIC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/brand/brand.ts +function brand(name) { + return { + kind: "transformation", + type: "brand", + reference: brand, + async: false, + name, + _run(dataset) { + return dataset; + } + }; +} + +// src/actions/bytes/bytes.ts +function bytes(requirement, message) { + return { + kind: "validation", + type: "bytes", + reference: bytes, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 !== this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/check/check.ts +function check(requirement, message) { + return { + kind: "validation", + type: "check", + reference: check, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/check/checkAsync.ts +function checkAsync(requirement, message) { + return { + kind: "validation", + type: "check", + reference: checkAsync, + async: true, + expects: null, + requirement, + message, + async _run(dataset, config2) { + if (dataset.typed && !await this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/checkItems/checkItems.ts +function checkItems(requirement, message) { + return { + kind: "validation", + type: "check_items", + reference: checkItems, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + for (let index = 0; index < dataset.value.length; index++) { + const item = dataset.value[index]; + if (!this.requirement(item, index, dataset.value)) { + _addIssue(this, "item", dataset, config2, { + input: item, + path: [ + { + type: "array", + origin: "value", + input: dataset.value, + key: index, + value: item + } + ] + }); + } + } + } + return dataset; + } + }; +} + +// src/actions/creditCard/creditCard.ts +var CREDIT_CARD_REGEX = /^(?:\d{14,19}|\d{4}(?: \d{3,6}){2,4}|\d{4}(?:-\d{3,6}){2,4})$/u; +var SANITIZE_REGEX = /[- ]/gu; +var PROVIDER_REGEX_LIST = [ + // American Express + /^3[47]\d{13}$/u, + // Diners Club + /^3(?:0[0-5]|[68]\d)\d{11,13}$/u, + // Discover + /^6(?:011|5\d{2})\d{12,15}$/u, + // JCB + /^(?:2131|1800|35\d{3})\d{11}$/u, + // Mastercard + /^5[1-5]\d{2}|(?:222\d|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}$/u, + // UnionPay + /^(?:6[27]\d{14,17}|81\d{14,17})$/u, + // Visa + /^4\d{12}(?:\d{3,6})?$/u +]; +function creditCard(message) { + return { + kind: "validation", + type: "credit_card", + reference: creditCard, + async: false, + expects: null, + requirement(input) { + let sanitized; + return CREDIT_CARD_REGEX.test(input) && // Remove any hyphens and blanks + (sanitized = input.replace(SANITIZE_REGEX, "")) && // Check if it matches a provider + PROVIDER_REGEX_LIST.some((regex2) => regex2.test(sanitized)) && // Check if passes luhn algorithm + _isLuhnAlgo(sanitized); + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "credit card", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/cuid2/cuid2.ts +function cuid2(message) { + return { + kind: "validation", + type: "cuid2", + reference: cuid2, + async: false, + expects: null, + requirement: CUID2_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "Cuid2", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/decimal/decimal.ts +function decimal(message) { + return { + kind: "validation", + type: "decimal", + reference: decimal, + async: false, + expects: null, + requirement: DECIMAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "decimal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/description/description.ts +function description(description_) { + return { + kind: "metadata", + type: "description", + reference: description, + description: description_ + }; +} + +// src/actions/email/email.ts +function email(message) { + return { + kind: "validation", + type: "email", + reference: email, + expects: null, + async: false, + requirement: EMAIL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "email", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/emoji/emoji.ts +function emoji(message) { + return { + kind: "validation", + type: "emoji", + reference: emoji, + async: false, + expects: null, + requirement: EMOJI_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "emoji", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/empty/empty.ts +function empty(message) { + return { + kind: "validation", + type: "empty", + reference: empty, + async: false, + expects: "0", + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length > 0) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/endsWith/endsWith.ts +function endsWith(requirement, message) { + return { + kind: "validation", + type: "ends_with", + reference: endsWith, + async: false, + expects: `"${requirement}"`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.endsWith(this.requirement)) { + _addIssue(this, "end", dataset, config2, { + received: `"${dataset.value.slice(-this.requirement.length)}"` + }); + } + return dataset; + } + }; +} + +// src/actions/everyItem/everyItem.ts +function everyItem(requirement, message) { + return { + kind: "validation", + type: "every_item", + reference: everyItem, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.every(this.requirement)) { + _addIssue(this, "item", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/excludes/excludes.ts +function excludes(requirement, message) { + const received = _stringify(requirement); + return { + kind: "validation", + type: "excludes", + reference: excludes, + async: false, + expects: `!${received}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.includes(this.requirement)) { + _addIssue(this, "content", dataset, config2, { received }); + } + return dataset; + } + }; +} + +// src/actions/filterItems/filterItems.ts +function filterItems(operation) { + return { + kind: "transformation", + type: "filter_items", + reference: filterItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.filter(this.operation); + return dataset; + } + }; +} + +// src/actions/findItem/findItem.ts +function findItem(operation) { + return { + kind: "transformation", + type: "find_item", + reference: findItem, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.find(this.operation); + return dataset; + } + }; +} + +// src/actions/finite/finite.ts +function finite(message) { + return { + kind: "validation", + type: "finite", + reference: finite, + async: false, + expects: null, + requirement: Number.isFinite, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "finite", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hash/hash.ts +var HASH_LENGTHS = { + md4: 32, + md5: 32, + sha1: 40, + sha256: 64, + sha384: 96, + sha512: 128, + ripemd128: 32, + ripemd160: 40, + tiger128: 32, + tiger160: 40, + tiger192: 48, + crc32: 8, + crc32b: 8, + adler32: 8 +}; +function hash(types, message) { + return { + kind: "validation", + type: "hash", + reference: hash, + expects: null, + async: false, + requirement: RegExp( + types.map((type) => `^[a-f0-9]{${HASH_LENGTHS[type]}}$`).join("|"), + "iu" + ), + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hash", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hexadecimal/hexadecimal.ts +function hexadecimal(message) { + return { + kind: "validation", + type: "hexadecimal", + reference: hexadecimal, + async: false, + expects: null, + requirement: HEXADECIMAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hexadecimal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hexColor/hexColor.ts +function hexColor(message) { + return { + kind: "validation", + type: "hex_color", + reference: hexColor, + async: false, + expects: null, + requirement: HEX_COLOR_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hex color", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/imei/imei.ts +function imei(message) { + return { + kind: "validation", + type: "imei", + reference: imei, + async: false, + expects: null, + requirement(input) { + return IMEI_REGEX.test(input) && _isLuhnAlgo(input); + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "IMEI", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/includes/includes.ts +function includes(requirement, message) { + const expects = _stringify(requirement); + return { + kind: "validation", + type: "includes", + reference: includes, + async: false, + expects, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.includes(this.requirement)) { + _addIssue(this, "content", dataset, config2, { + received: `!${expects}` + }); + } + return dataset; + } + }; +} + +// src/actions/integer/integer.ts +function integer(message) { + return { + kind: "validation", + type: "integer", + reference: integer, + async: false, + expects: null, + requirement: Number.isInteger, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "integer", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ip/ip.ts +function ip(message) { + return { + kind: "validation", + type: "ip", + reference: ip, + async: false, + expects: null, + requirement: IP_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IP", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ipv4/ipv4.ts +function ipv4(message) { + return { + kind: "validation", + type: "ipv4", + reference: ipv4, + async: false, + expects: null, + requirement: IPV4_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IPv4", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ipv6/ipv6.ts +function ipv6(message) { + return { + kind: "validation", + type: "ipv6", + reference: ipv6, + async: false, + expects: null, + requirement: IPV6_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IPv6", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoDate/isoDate.ts +function isoDate(message) { + return { + kind: "validation", + type: "iso_date", + reference: isoDate, + async: false, + expects: null, + requirement: ISO_DATE_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "date", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoDateTime/isoDateTime.ts +function isoDateTime(message) { + return { + kind: "validation", + type: "iso_date_time", + reference: isoDateTime, + async: false, + expects: null, + requirement: ISO_DATE_TIME_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "date-time", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTime/isoTime.ts +function isoTime(message) { + return { + kind: "validation", + type: "iso_time", + reference: isoTime, + async: false, + expects: null, + requirement: ISO_TIME_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "time", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTimeSecond/isoTimeSecond.ts +function isoTimeSecond(message) { + return { + kind: "validation", + type: "iso_time_second", + reference: isoTimeSecond, + async: false, + expects: null, + requirement: ISO_TIME_SECOND_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "time-second", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTimestamp/isoTimestamp.ts +function isoTimestamp(message) { + return { + kind: "validation", + type: "iso_timestamp", + reference: isoTimestamp, + async: false, + expects: null, + requirement: ISO_TIMESTAMP_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "timestamp", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoWeek/isoWeek.ts +function isoWeek(message) { + return { + kind: "validation", + type: "iso_week", + reference: isoWeek, + async: false, + expects: null, + requirement: ISO_WEEK_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "week", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/length/length.ts +function length(requirement, message) { + return { + kind: "validation", + type: "length", + reference: length, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length !== this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/mac/mac.ts +function mac(message) { + return { + kind: "validation", + type: "mac", + reference: mac, + async: false, + expects: null, + requirement: MAC_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mac48/mac48.ts +function mac48(message) { + return { + kind: "validation", + type: "mac48", + reference: mac48, + async: false, + expects: null, + requirement: MAC48_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "48-bit MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mac64/mac64.ts +function mac64(message) { + return { + kind: "validation", + type: "mac64", + reference: mac64, + async: false, + expects: null, + requirement: MAC64_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "64-bit MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mapItems/mapItems.ts +function mapItems(operation) { + return { + kind: "transformation", + type: "map_items", + reference: mapItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.map(this.operation); + return dataset; + } + }; +} + +// src/actions/maxBytes/maxBytes.ts +function maxBytes(requirement, message) { + return { + kind: "validation", + type: "max_bytes", + reference: maxBytes, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 > this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/maxLength/maxLength.ts +function maxLength(requirement, message) { + return { + kind: "validation", + type: "max_length", + reference: maxLength, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length > this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/maxSize/maxSize.ts +function maxSize(requirement, message) { + return { + kind: "validation", + type: "max_size", + reference: maxSize, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size > this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/maxValue/maxValue.ts +function maxValue(requirement, message) { + return { + kind: "validation", + type: "max_value", + reference: maxValue, + async: false, + expects: `<=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value > this.requirement) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/mimeType/mimeType.ts +function mimeType(requirement, message) { + return { + kind: "validation", + type: "mime_type", + reference: mimeType, + async: false, + expects: _joinExpects( + requirement.map((option) => `"${option}"`), + "|" + ), + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.includes(dataset.value.type)) { + _addIssue(this, "MIME type", dataset, config2, { + received: `"${dataset.value.type}"` + }); + } + return dataset; + } + }; +} + +// src/actions/minBytes/minBytes.ts +function minBytes(requirement, message) { + return { + kind: "validation", + type: "min_bytes", + reference: minBytes, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 < this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/minLength/minLength.ts +function minLength(requirement, message) { + return { + kind: "validation", + type: "min_length", + reference: minLength, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length < this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/minSize/minSize.ts +function minSize(requirement, message) { + return { + kind: "validation", + type: "min_size", + reference: minSize, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size < this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/minValue/minValue.ts +function minValue(requirement, message) { + return { + kind: "validation", + type: "min_value", + reference: minValue, + async: false, + expects: `>=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value < this.requirement) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/multipleOf/multipleOf.ts +function multipleOf(requirement, message) { + return { + kind: "validation", + type: "multiple_of", + reference: multipleOf, + async: false, + expects: `%${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value % this.requirement !== 0) { + _addIssue(this, "multiple", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/nonEmpty/nonEmpty.ts +function nonEmpty(message) { + return { + kind: "validation", + type: "non_empty", + reference: nonEmpty, + async: false, + expects: "!0", + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length === 0) { + _addIssue(this, "length", dataset, config2, { + received: "0" + }); + } + return dataset; + } + }; +} + +// src/actions/normalize/normalize.ts +function normalize(form) { + return { + kind: "transformation", + type: "normalize", + reference: normalize, + async: false, + form, + _run(dataset) { + dataset.value = dataset.value.normalize(this.form); + return dataset; + } + }; +} + +// src/actions/notBytes/notBytes.ts +function notBytes(requirement, message) { + return { + kind: "validation", + type: "not_bytes", + reference: notBytes, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 === this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/notLength/notLength.ts +function notLength(requirement, message) { + return { + kind: "validation", + type: "not_length", + reference: notLength, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length === this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/notSize/notSize.ts +function notSize(requirement, message) { + return { + kind: "validation", + type: "not_size", + reference: notSize, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size === this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/notValue/notValue.ts +function notValue(requirement, message) { + return { + kind: "validation", + type: "not_value", + reference: notValue, + async: false, + expects: requirement instanceof Date ? `!${requirement.toJSON()}` : `!${_stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && this.requirement <= dataset.value && this.requirement >= dataset.value) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/octal/octal.ts +function octal(message) { + return { + kind: "validation", + type: "octal", + reference: octal, + async: false, + expects: null, + requirement: OCTAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "octal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/partialCheck/utils/_isPartiallyTyped/_isPartiallyTyped.ts +function _isPartiallyTyped(dataset, pathList) { + if (dataset.issues) { + for (const path of pathList) { + for (const issue of dataset.issues) { + let typed = false; + const bound = Math.min(path.length, issue.path?.length ?? 0); + for (let index = 0; index < bound; index++) { + if (path[index] !== issue.path[index].key) { + typed = true; + break; + } + } + if (!typed) { + return false; + } + } + } + } + return true; +} + +// src/actions/partialCheck/partialCheck.ts +function partialCheck(pathList, requirement, message) { + return { + kind: "validation", + type: "partial_check", + reference: partialCheck, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (_isPartiallyTyped(dataset, pathList) && // @ts-expect-error + !this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/partialCheck/partialCheckAsync.ts +function partialCheckAsync(pathList, requirement, message) { + return { + kind: "validation", + type: "partial_check", + reference: partialCheckAsync, + async: true, + expects: null, + requirement, + message, + async _run(dataset, config2) { + if (_isPartiallyTyped(dataset, pathList) && // @ts-expect-error + !await this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/rawCheck/rawCheck.ts +function rawCheck(action) { + return { + kind: "validation", + type: "raw_check", + reference: rawCheck, + async: false, + expects: null, + _run(dataset, config2) { + action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info) + }); + return dataset; + } + }; +} + +// src/actions/rawCheck/rawCheckAsync.ts +function rawCheckAsync(action) { + return { + kind: "validation", + type: "raw_check", + reference: rawCheckAsync, + async: true, + expects: null, + async _run(dataset, config2) { + await action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info) + }); + return dataset; + } + }; +} + +// src/actions/rawTransform/rawTransform.ts +function rawTransform(action) { + return { + kind: "transformation", + type: "raw_transform", + reference: rawTransform, + async: false, + _run(dataset, config2) { + const output = action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info), + NEVER: null + }); + if (dataset.issues) { + dataset.typed = false; + } else { + dataset.value = output; + } + return dataset; + } + }; +} + +// src/actions/rawTransform/rawTransformAsync.ts +function rawTransformAsync(action) { + return { + kind: "transformation", + type: "raw_transform", + reference: rawTransformAsync, + async: true, + async _run(dataset, config2) { + const output = await action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info), + NEVER: null + }); + if (dataset.issues) { + dataset.typed = false; + } else { + dataset.value = output; + } + return dataset; + } + }; +} + +// src/actions/readonly/readonly.ts +function readonly() { + return { + kind: "transformation", + type: "readonly", + reference: readonly, + async: false, + _run(dataset) { + return dataset; + } + }; +} + +// src/actions/reduceItems/reduceItems.ts +function reduceItems(operation, initial) { + return { + kind: "transformation", + type: "reduce_items", + reference: reduceItems, + async: false, + operation, + initial, + _run(dataset) { + dataset.value = dataset.value.reduce(this.operation, this.initial); + return dataset; + } + }; +} + +// src/actions/regex/regex.ts +function regex(requirement, message) { + return { + kind: "validation", + type: "regex", + reference: regex, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "format", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/safeInteger/safeInteger.ts +function safeInteger(message) { + return { + kind: "validation", + type: "safe_integer", + reference: safeInteger, + async: false, + expects: null, + requirement: Number.isSafeInteger, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "safe integer", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/size/size.ts +function size(requirement, message) { + return { + kind: "validation", + type: "size", + reference: size, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size !== this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/someItem/someItem.ts +function someItem(requirement, message) { + return { + kind: "validation", + type: "some_item", + reference: someItem, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.some(this.requirement)) { + _addIssue(this, "item", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/sortItems/sortItems.ts +function sortItems(operation) { + return { + kind: "transformation", + type: "sort_items", + reference: sortItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.sort(this.operation); + return dataset; + } + }; +} + +// src/actions/startsWith/startsWith.ts +function startsWith(requirement, message) { + return { + kind: "validation", + type: "starts_with", + reference: startsWith, + async: false, + expects: `"${requirement}"`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.startsWith(this.requirement)) { + _addIssue(this, "start", dataset, config2, { + received: `"${dataset.value.slice(0, this.requirement.length)}"` + }); + } + return dataset; + } + }; +} + +// src/actions/toLowerCase/toLowerCase.ts +function toLowerCase() { + return { + kind: "transformation", + type: "to_lower_case", + reference: toLowerCase, + async: false, + _run(dataset) { + dataset.value = dataset.value.toLowerCase(); + return dataset; + } + }; +} + +// src/actions/toMaxValue/toMaxValue.ts +function toMaxValue(requirement) { + return { + kind: "transformation", + type: "to_max_value", + reference: toMaxValue, + async: false, + requirement, + _run(dataset) { + dataset.value = dataset.value > this.requirement ? this.requirement : dataset.value; + return dataset; + } + }; +} + +// src/actions/toMinValue/toMinValue.ts +function toMinValue(requirement) { + return { + kind: "transformation", + type: "to_min_value", + reference: toMinValue, + async: false, + requirement, + _run(dataset) { + dataset.value = dataset.value < this.requirement ? this.requirement : dataset.value; + return dataset; + } + }; +} + +// src/actions/toUpperCase/toUpperCase.ts +function toUpperCase() { + return { + kind: "transformation", + type: "to_upper_case", + reference: toUpperCase, + async: false, + _run(dataset) { + dataset.value = dataset.value.toUpperCase(); + return dataset; + } + }; +} + +// src/actions/transform/transform.ts +function transform(operation) { + return { + kind: "transformation", + type: "transform", + reference: transform, + async: false, + operation, + _run(dataset) { + dataset.value = this.operation(dataset.value); + return dataset; + } + }; +} + +// src/actions/transform/transformAsync.ts +function transformAsync(operation) { + return { + kind: "transformation", + type: "transform", + reference: transformAsync, + async: true, + operation, + async _run(dataset) { + dataset.value = await this.operation(dataset.value); + return dataset; + } + }; +} + +// src/actions/trim/trim.ts +function trim() { + return { + kind: "transformation", + type: "trim", + reference: trim, + async: false, + _run(dataset) { + dataset.value = dataset.value.trim(); + return dataset; + } + }; +} + +// src/actions/trimEnd/trimEnd.ts +function trimEnd() { + return { + kind: "transformation", + type: "trim_end", + reference: trimEnd, + async: false, + _run(dataset) { + dataset.value = dataset.value.trimEnd(); + return dataset; + } + }; +} + +// src/actions/trimStart/trimStart.ts +function trimStart() { + return { + kind: "transformation", + type: "trim_start", + reference: trimStart, + async: false, + _run(dataset) { + dataset.value = dataset.value.trimStart(); + return dataset; + } + }; +} + +// src/actions/ulid/ulid.ts +function ulid(message) { + return { + kind: "validation", + type: "ulid", + reference: ulid, + async: false, + expects: null, + requirement: ULID_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "ULID", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/url/url.ts +function url(message) { + return { + kind: "validation", + type: "url", + reference: url, + async: false, + expects: null, + requirement(input) { + try { + new URL(input); + return true; + } catch { + return false; + } + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "URL", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/uuid/uuid.ts +function uuid(message) { + return { + kind: "validation", + type: "uuid", + reference: uuid, + async: false, + expects: null, + requirement: UUID_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "UUID", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/value/value.ts +function value(requirement, message) { + return { + kind: "validation", + type: "value", + reference: value, + async: false, + expects: requirement instanceof Date ? requirement.toJSON() : _stringify(requirement), + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !(this.requirement <= dataset.value && this.requirement >= dataset.value)) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/methods/config/config.ts +function config(schema, config2) { + return { + ...schema, + _run(dataset, config_) { + return schema._run(dataset, { ...config_, ...config2 }); + } + }; +} + +// src/methods/getFallback/getFallback.ts +function getFallback(schema, dataset, config2) { + return typeof schema.fallback === "function" ? ( + // @ts-expect-error + schema.fallback(dataset, config2) + ) : ( + // @ts-expect-error + schema.fallback + ); +} + +// src/methods/fallback/fallback.ts +function fallback(schema, fallback2) { + return { + ...schema, + fallback: fallback2, + _run(dataset, config2) { + const outputDataset = schema._run(dataset, config2); + return outputDataset.issues ? { typed: true, value: getFallback(this, outputDataset, config2) } : outputDataset; + } + }; +} + +// src/methods/fallback/fallbackAsync.ts +function fallbackAsync(schema, fallback2) { + return { + ...schema, + fallback: fallback2, + async: true, + async _run(dataset, config2) { + const outputDataset = await schema._run(dataset, config2); + return outputDataset.issues ? ( + // @ts-expect-error + { typed: true, value: await getFallback(this, outputDataset, config2) } + ) : outputDataset; + } + }; +} + +// src/methods/flatten/flatten.ts +function flatten(issues) { + const flatErrors = {}; + for (const issue of issues) { + if (issue.path) { + const dotPath = getDotPath(issue); + if (dotPath) { + if (!flatErrors.nested) { + flatErrors.nested = {}; + } + if (flatErrors.nested[dotPath]) { + flatErrors.nested[dotPath].push(issue.message); + } else { + flatErrors.nested[dotPath] = [issue.message]; + } + } else { + if (flatErrors.other) { + flatErrors.other.push(issue.message); + } else { + flatErrors.other = [issue.message]; + } + } + } else { + if (flatErrors.root) { + flatErrors.root.push(issue.message); + } else { + flatErrors.root = [issue.message]; + } + } + } + return flatErrors; +} + +// src/methods/forward/forward.ts +function forward(action, pathKeys) { + return { + ...action, + _run(dataset, config2) { + const prevIssues = dataset.issues && [...dataset.issues]; + action._run(dataset, config2); + if (dataset.issues) { + for (const issue of dataset.issues) { + if (!prevIssues?.includes(issue)) { + let pathInput = dataset.value; + for (const key of pathKeys) { + const pathValue = pathInput[key]; + const pathItem = { + type: "unknown", + origin: "value", + input: pathInput, + key, + value: pathValue + }; + if (issue.path) { + issue.path.push(pathItem); + } else { + issue.path = [pathItem]; + } + if (!pathValue) { + break; + } + pathInput = pathValue; + } + } + } + } + return dataset; + } + }; +} + +// src/methods/forward/forwardAsync.ts +function forwardAsync(action, pathKeys) { + return { + ...action, + async: true, + async _run(dataset, config2) { + const prevIssues = dataset.issues && [...dataset.issues]; + await action._run(dataset, config2); + if (dataset.issues) { + for (const issue of dataset.issues) { + if (!prevIssues?.includes(issue)) { + let pathInput = dataset.value; + for (const key of pathKeys) { + const pathValue = pathInput[key]; + const pathItem = { + type: "unknown", + origin: "value", + input: pathInput, + key, + value: pathValue + }; + if (issue.path) { + issue.path.push(pathItem); + } else { + issue.path = [pathItem]; + } + if (!pathValue) { + break; + } + pathInput = pathValue; + } + } + } + } + return dataset; + } + }; +} + +// src/methods/getDefault/getDefault.ts +function getDefault(schema, dataset, config2) { + return typeof schema.default === "function" ? ( + // @ts-expect-error + schema.default(dataset, config2) + ) : ( + // @ts-expect-error + schema.default + ); +} + +// src/methods/getDefaults/getDefaults.ts +function getDefaults(schema) { + if ("entries" in schema) { + const object2 = {}; + for (const key in schema.entries) { + object2[key] = getDefaults(schema.entries[key]); + } + return object2; + } + if ("items" in schema) { + return schema.items.map(getDefaults); + } + return getDefault(schema); +} + +// src/methods/getDefaults/getDefaultsAsync.ts +async function getDefaultsAsync(schema) { + if ("entries" in schema) { + return Object.fromEntries( + await Promise.all( + Object.entries(schema.entries).map(async ([key, value2]) => [ + key, + await getDefaultsAsync(value2) + ]) + ) + ); + } + if ("items" in schema) { + return Promise.all(schema.items.map(getDefaultsAsync)); + } + return getDefault(schema); +} + +// src/methods/getFallbacks/getFallbacks.ts +function getFallbacks(schema) { + if ("entries" in schema) { + const object2 = {}; + for (const key in schema.entries) { + object2[key] = getFallbacks(schema.entries[key]); + } + return object2; + } + if ("items" in schema) { + return schema.items.map(getFallbacks); + } + return getFallback(schema); +} + +// src/methods/getFallbacks/getFallbacksAsync.ts +async function getFallbacksAsync(schema) { + if ("entries" in schema) { + return Object.fromEntries( + await Promise.all( + Object.entries(schema.entries).map(async ([key, value2]) => [ + key, + await getFallbacksAsync(value2) + ]) + ) + ); + } + if ("items" in schema) { + return Promise.all(schema.items.map(getFallbacksAsync)); + } + return getFallback(schema); +} + +// src/methods/is/is.ts +function is(schema, input) { + return !schema._run({ typed: false, value: input }, { abortEarly: true }).issues; +} + +// src/schemas/any/any.ts +function any() { + return { + kind: "schema", + type: "any", + reference: any, + expects: "any", + async: false, + _run(dataset) { + dataset.typed = true; + return dataset; + } + }; +} + +// src/schemas/array/array.ts +function array(item, message) { + return { + kind: "schema", + type: "array", + reference: array, + expects: "Array", + async: false, + item, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < input.length; key++) { + const value2 = input[key]; + const itemDataset = this.item._run({ typed: false, value: value2 }, config2); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/array/arrayAsync.ts +function arrayAsync(item, message) { + return { + kind: "schema", + type: "array", + reference: arrayAsync, + expects: "Array", + async: true, + item, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + input.map((value2) => this.item._run({ typed: false, value: value2 }, config2)) + ); + for (let key = 0; key < itemDatasets.length; key++) { + const itemDataset = itemDatasets[key]; + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: input[key] + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/bigint/bigint.ts +function bigint(message) { + return { + kind: "schema", + type: "bigint", + reference: bigint, + expects: "bigint", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "bigint") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/blob/blob.ts +function blob(message) { + return { + kind: "schema", + type: "blob", + reference: blob, + expects: "Blob", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Blob) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/boolean/boolean.ts +function boolean(message) { + return { + kind: "schema", + type: "boolean", + reference: boolean, + expects: "boolean", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "boolean") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/custom/custom.ts +function custom(check2, message) { + return { + kind: "schema", + type: "custom", + reference: custom, + expects: "unknown", + async: false, + check: check2, + message, + _run(dataset, config2) { + if (this.check(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/custom/customAsync.ts +function customAsync(check2, message) { + return { + kind: "schema", + type: "custom", + reference: customAsync, + expects: "unknown", + async: true, + check: check2, + message, + async _run(dataset, config2) { + if (await this.check(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/date/date.ts +function date(message) { + return { + kind: "schema", + type: "date", + reference: date, + expects: "Date", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Date) { + if (!isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2, { + received: '"Invalid Date"' + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/enum/enum.ts +function enum_(enum__, message) { + const options = Object.entries(enum__).filter(([key]) => isNaN(+key)).map(([, value2]) => value2); + return { + kind: "schema", + type: "enum", + reference: enum_, + expects: _joinExpects(options.map(_stringify), "|"), + async: false, + enum: enum__, + options, + message, + _run(dataset, config2) { + if (this.options.includes(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/file/file.ts +function file(message) { + return { + kind: "schema", + type: "file", + reference: file, + expects: "File", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof File) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/function/function.ts +function function_(message) { + return { + kind: "schema", + type: "function", + reference: function_, + expects: "Function", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "function") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/instance/instance.ts +function instance(class_, message) { + return { + kind: "schema", + type: "instance", + reference: instance, + expects: class_.name, + async: false, + class: class_, + message, + _run(dataset, config2) { + if (dataset.value instanceof this.class) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/intersect/utils/_merge/_merge.ts +function _merge(value1, value2) { + if (typeof value1 === typeof value2) { + if (value1 === value2 || value1 instanceof Date && value2 instanceof Date && +value1 === +value2) { + return { value: value1 }; + } + if (value1 && value2 && value1.constructor === Object && value2.constructor === Object) { + for (const key in value2) { + if (key in value1) { + const dataset = _merge(value1[key], value2[key]); + if (dataset.issue) { + return dataset; + } + value1[key] = dataset.value; + } else { + value1[key] = value2[key]; + } + } + return { value: value1 }; + } + if (Array.isArray(value1) && Array.isArray(value2)) { + if (value1.length === value2.length) { + for (let index = 0; index < value1.length; index++) { + const dataset = _merge(value1[index], value2[index]); + if (dataset.issue) { + return dataset; + } + value1[index] = dataset.value; + } + return { value: value1 }; + } + } + } + return { issue: true }; +} + +// src/schemas/intersect/intersect.ts +function intersect(options, message) { + return { + kind: "schema", + type: "intersect", + reference: intersect, + expects: _joinExpects( + options.map((option) => option.expects), + "&" + ), + async: false, + options, + message, + _run(dataset, config2) { + if (this.options.length) { + const input = dataset.value; + let outputs; + dataset.typed = true; + for (const schema of this.options) { + const optionDataset = schema._run( + { typed: false, value: input }, + config2 + ); + if (optionDataset.issues) { + if (dataset.issues) { + dataset.issues.push(...optionDataset.issues); + } else { + dataset.issues = optionDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!optionDataset.typed) { + dataset.typed = false; + } + if (dataset.typed) { + if (outputs) { + outputs.push(optionDataset.value); + } else { + outputs = [optionDataset.value]; + } + } + } + if (dataset.typed) { + dataset.value = outputs[0]; + for (let index = 1; index < outputs.length; index++) { + const mergeDataset = _merge(dataset.value, outputs[index]); + if (mergeDataset.issue) { + _addIssue(this, "type", dataset, config2, { + received: "unknown" + }); + break; + } + dataset.value = mergeDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/intersect/intersectAsync.ts +function intersectAsync(options, message) { + return { + kind: "schema", + type: "intersect", + reference: intersectAsync, + expects: _joinExpects( + options.map((option) => option.expects), + "&" + ), + async: true, + options, + message, + async _run(dataset, config2) { + if (this.options.length) { + const input = dataset.value; + let outputs; + dataset.typed = true; + const optionDatasets = await Promise.all( + this.options.map( + (schema) => schema._run({ typed: false, value: input }, config2) + ) + ); + for (const optionDataset of optionDatasets) { + if (optionDataset.issues) { + if (dataset.issues) { + dataset.issues.push(...optionDataset.issues); + } else { + dataset.issues = optionDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!optionDataset.typed) { + dataset.typed = false; + } + if (dataset.typed) { + if (outputs) { + outputs.push(optionDataset.value); + } else { + outputs = [optionDataset.value]; + } + } + } + if (dataset.typed) { + dataset.value = outputs[0]; + for (let index = 1; index < outputs.length; index++) { + const mergeDataset = _merge(dataset.value, outputs[index]); + if (mergeDataset.issue) { + _addIssue(this, "type", dataset, config2, { + received: "unknown" + }); + break; + } + dataset.value = mergeDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/lazy/lazy.ts +function lazy(getter) { + return { + kind: "schema", + type: "lazy", + reference: lazy, + expects: "unknown", + async: false, + getter, + _run(dataset, config2) { + return this.getter(dataset.value)._run(dataset, config2); + } + }; +} + +// src/schemas/lazy/lazyAsync.ts +function lazyAsync(getter) { + return { + kind: "schema", + type: "lazy", + reference: lazyAsync, + expects: "unknown", + async: true, + getter, + async _run(dataset, config2) { + return (await this.getter(dataset.value))._run(dataset, config2); + } + }; +} + +// src/schemas/literal/literal.ts +function literal(literal_, message) { + return { + kind: "schema", + type: "literal", + reference: literal, + expects: _stringify(literal_), + async: false, + literal: literal_, + message, + _run(dataset, config2) { + if (dataset.value === this.literal) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseObject/looseObject.ts +function looseObject(entries, message) { + return { + kind: "schema", + type: "loose_object", + reference: looseObject, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + dataset.value[key] = input[key]; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseObject/looseObjectAsync.ts +function looseObjectAsync(entries, message) { + return { + kind: "schema", + type: "loose_object", + reference: looseObjectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + dataset.value[key] = input[key]; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseTuple/looseTuple.ts +function looseTuple(items, message) { + return { + kind: "schema", + type: "loose_tuple", + reference: looseTuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + dataset.value.push(input[key]); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseTuple/looseTupleAsync.ts +function looseTupleAsync(items, message) { + return { + kind: "schema", + type: "loose_tuple", + reference: looseTupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + dataset.value.push(input[key]); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/map/map.ts +function map(key, value2, message) { + return { + kind: "schema", + type: "map", + reference: map, + expects: "Map", + async: false, + key, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Map) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Map(); + for (const [inputKey, inputValue] of input) { + const keyDataset = this.key._run( + { typed: false, value: inputKey }, + config2 + ); + if (keyDataset.issues) { + const pathItem = { + type: "map", + origin: "key", + input, + key: inputKey, + value: inputValue + }; + for (const issue of keyDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + const valueDataset = this.value._run( + { typed: false, value: inputValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "map", + origin: "value", + input, + key: inputKey, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + dataset.value.set(keyDataset.value, valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/map/mapAsync.ts +function mapAsync(key, value2, message) { + return { + kind: "schema", + type: "map", + reference: mapAsync, + expects: "Map", + async: true, + key, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Map) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Map(); + const datasets = await Promise.all( + [...input].map( + ([inputKey, inputValue]) => Promise.all([ + inputKey, + inputValue, + this.key._run({ typed: false, value: inputKey }, config2), + this.value._run({ typed: false, value: inputValue }, config2) + ]) + ) + ); + for (const [ + inputKey, + inputValue, + keyDataset, + valueDataset + ] of datasets) { + if (keyDataset.issues) { + const pathItem = { + type: "map", + origin: "key", + input, + key: inputKey, + value: inputValue + }; + for (const issue of keyDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (valueDataset.issues) { + const pathItem = { + type: "map", + origin: "value", + input, + key: inputKey, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + dataset.value.set(keyDataset.value, valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/nan/nan.ts +function nan(message) { + return { + kind: "schema", + type: "nan", + reference: nan, + expects: "NaN", + async: false, + message, + _run(dataset, config2) { + if (Number.isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/never/never.ts +function never(message) { + return { + kind: "schema", + type: "never", + reference: never, + expects: "never", + async: false, + message, + _run(dataset, config2) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + }; +} + +// src/schemas/nonNullable/nonNullable.ts +function nonNullable(wrapped, message) { + return { + kind: "schema", + type: "non_nullable", + reference: nonNullable, + expects: "!null", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === null) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullable/nonNullableAsync.ts +function nonNullableAsync(wrapped, message) { + return { + kind: "schema", + type: "non_nullable", + reference: nonNullableAsync, + expects: "!null", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === null) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullish/nonNullish.ts +function nonNullish(wrapped, message) { + return { + kind: "schema", + type: "non_nullish", + reference: nonNullish, + expects: "(!null & !undefined)", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullish/nonNullishAsync.ts +function nonNullishAsync(wrapped, message) { + return { + kind: "schema", + type: "non_nullish", + reference: nonNullishAsync, + expects: "(!null & !undefined)", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonOptional/nonOptional.ts +function nonOptional(wrapped, message) { + return { + kind: "schema", + type: "non_optional", + reference: nonOptional, + expects: "!undefined", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonOptional/nonOptionalAsync.ts +function nonOptionalAsync(wrapped, message) { + return { + kind: "schema", + type: "non_optional", + reference: nonOptionalAsync, + expects: "!undefined", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/null/null.ts +function null_(message) { + return { + kind: "schema", + type: "null", + reference: null_, + expects: "null", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === null) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/nullable/nullable.ts +function nullable(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullable", + reference: nullable, + expects: `(${wrapped.expects} | null)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === null) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullable/nullableAsync.ts +function nullableAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullable", + reference: nullableAsync, + expects: `(${wrapped.expects} | null)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === null) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullish/nullish.ts +function nullish(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullish", + reference: nullish, + expects: `(${wrapped.expects} | null | undefined)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null || dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullish/nullishAsync.ts +function nullishAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullish", + reference: nullishAsync, + expects: `(${wrapped.expects} | null | undefined)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null || dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/number/number.ts +function number(message) { + return { + kind: "schema", + type: "number", + reference: number, + expects: "number", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "number" && !isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/object/object.ts +function object(entries, message) { + return { + kind: "schema", + type: "object", + reference: object, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/object/objectAsync.ts +function objectAsync(entries, message) { + return { + kind: "schema", + type: "object", + reference: objectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/objectWithRest/objectWithRest.ts +function objectWithRest(entries, rest, message) { + return { + kind: "schema", + type: "object_with_rest", + reference: objectWithRest, + expects: "Object", + async: false, + entries, + rest, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + const value2 = input[key]; + const valueDataset = this.rest._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value[key] = valueDataset.value; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/objectWithRest/objectWithRestAsync.ts +function objectWithRestAsync(entries, rest, message) { + return { + kind: "schema", + type: "object_with_rest", + reference: objectWithRestAsync, + expects: "Object", + async: true, + entries, + rest, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const [normalDatasets, restDatasets] = await Promise.all([ + // Parse schema of each normal entry + // Hint: We do not distinguish between missing and `undefined` entries. + // The reason for this decision is that it reduces the bundle size, and + // we also expect that most users will expect this behavior. + Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ), + // Parse other entries with rest schema + // Hint: We exclude specific keys for security reasons + Promise.all( + Object.entries(input).filter( + ([key]) => _isValidObjectKey(input, key) && !(key in this.entries) + ).map( + async ([key, value2]) => [ + key, + value2, + await this.rest._run({ typed: false, value: value2 }, config2) + ] + ) + ) + ]); + for (const [key, value2, valueDataset] of normalDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const [key, value2, valueDataset] of restDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/optional/optional.ts +function optional(wrapped, ...args) { + const schema = { + kind: "schema", + type: "optional", + reference: optional, + expects: `(${wrapped.expects} | undefined)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === void 0) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/optional/optionalAsync.ts +function optionalAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "optional", + reference: optionalAsync, + expects: `(${wrapped.expects} | undefined)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === void 0) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/picklist/picklist.ts +function picklist(options, message) { + return { + kind: "schema", + type: "picklist", + reference: picklist, + expects: _joinExpects(options.map(_stringify), "|"), + async: false, + options, + message, + _run(dataset, config2) { + if (this.options.includes(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/promise/promise.ts +function promise(message) { + return { + kind: "schema", + type: "promise", + reference: promise, + expects: "Promise", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Promise) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/record/record.ts +function record(key, value2, message) { + return { + kind: "schema", + type: "record", + reference: record, + expects: "Object", + async: false, + key, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const entryKey in input) { + if (_isValidObjectKey(input, entryKey)) { + const entryValue = input[entryKey]; + const keyDataset = this.key._run( + { typed: false, value: entryKey }, + config2 + ); + if (keyDataset.issues) { + const pathItem = { + type: "object", + origin: "key", + input, + key: entryKey, + value: entryValue + }; + for (const issue of keyDataset.issues) { + issue.path = [pathItem]; + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + const valueDataset = this.value._run( + { typed: false, value: entryValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key: entryKey, + value: entryValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + if (keyDataset.typed) { + dataset.value[keyDataset.value] = valueDataset.value; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/record/recordAsync.ts +function recordAsync(key, value2, message) { + return { + kind: "schema", + type: "record", + reference: recordAsync, + expects: "Object", + async: true, + key, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const datasets = await Promise.all( + Object.entries(input).filter(([key2]) => _isValidObjectKey(input, key2)).map( + ([entryKey, entryValue]) => Promise.all([ + entryKey, + entryValue, + this.key._run({ typed: false, value: entryKey }, config2), + this.value._run({ typed: false, value: entryValue }, config2) + ]) + ) + ); + for (const [ + entryKey, + entryValue, + keyDataset, + valueDataset + ] of datasets) { + if (keyDataset.issues) { + const pathItem = { + type: "object", + origin: "key", + input, + key: entryKey, + value: entryValue + }; + for (const issue of keyDataset.issues) { + issue.path = [pathItem]; + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key: entryKey, + value: entryValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + if (keyDataset.typed) { + dataset.value[keyDataset.value] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/set/set.ts +function set(value2, message) { + return { + kind: "schema", + type: "set", + reference: set, + expects: "Set", + async: false, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Set) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Set(); + for (const inputValue of input) { + const valueDataset = this.value._run( + { typed: false, value: inputValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "set", + origin: "value", + input, + key: null, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value.add(valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/set/setAsync.ts +function setAsync(value2, message) { + return { + kind: "schema", + type: "set", + reference: setAsync, + expects: "Set", + async: true, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Set) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Set(); + const valueDatasets = await Promise.all( + [...input].map( + async (inputValue) => [ + inputValue, + await this.value._run( + { typed: false, value: inputValue }, + config2 + ) + ] + ) + ); + for (const [inputValue, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "set", + origin: "value", + input, + key: null, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value.add(valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictObject/strictObject.ts +function strictObject(entries, message) { + return { + kind: "schema", + type: "strict_object", + reference: strictObject, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (!(key in this.entries)) { + const value2 = input[key]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "object", + origin: "value", + input, + key, + value: value2 + } + ] + }); + break; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictObject/strictObjectAsync.ts +function strictObjectAsync(entries, message) { + return { + kind: "schema", + type: "strict_object", + reference: strictObjectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (!(key in this.entries)) { + const value2 = input[key]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "object", + origin: "value", + input, + key, + value: value2 + } + ] + }); + break; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictTuple/strictTuple.ts +function strictTuple(items, message) { + return { + kind: "schema", + type: "strict_tuple", + reference: strictTuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!(dataset.issues && config2.abortEarly) && this.items.length < input.length) { + const value2 = input[items.length]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "array", + origin: "value", + input, + key: this.items.length, + value: value2 + } + ] + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictTuple/strictTupleAsync.ts +function strictTupleAsync(items, message) { + return { + kind: "schema", + type: "strict_tuple", + reference: strictTupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!(dataset.issues && config2.abortEarly) && this.items.length < input.length) { + const value2 = input[items.length]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "array", + origin: "value", + input, + key: this.items.length, + value: value2 + } + ] + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/string/string.ts +function string(message) { + return { + kind: "schema", + type: "string", + reference: string, + expects: "string", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "string") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/symbol/symbol.ts +function symbol(message) { + return { + kind: "schema", + type: "symbol", + reference: symbol, + expects: "symbol", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "symbol") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tuple/tuple.ts +function tuple(items, message) { + return { + kind: "schema", + type: "tuple", + reference: tuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tuple/tupleAsync.ts +function tupleAsync(items, message) { + return { + kind: "schema", + type: "tuple", + reference: tupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tupleWithRest/tupleWithRest.ts +function tupleWithRest(items, rest, message) { + return { + kind: "schema", + type: "tuple_with_rest", + reference: tupleWithRest, + expects: "Array", + async: false, + items, + rest, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + const value2 = input[key]; + const itemDataset = this.rest._run({ typed: false, value: value2 }, config2); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tupleWithRest/tupleWithRestAsync.ts +function tupleWithRestAsync(items, rest, message) { + return { + kind: "schema", + type: "tuple_with_rest", + reference: tupleWithRestAsync, + expects: "Array", + async: true, + items, + rest, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const [normalDatasets, restDatasets] = await Promise.all([ + // Parse schema of each normal item + Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ), + // Parse other items with rest schema + Promise.all( + input.slice(this.items.length).map(async (value2, key) => { + return [ + key + this.items.length, + value2, + await this.rest._run({ typed: false, value: value2 }, config2) + ]; + }) + ) + ]); + for (const [key, value2, itemDataset] of normalDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (const [key, value2, itemDataset] of restDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/undefined/undefined.ts +function undefined_(message) { + return { + kind: "schema", + type: "undefined", + reference: undefined_, + expects: "undefined", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/union/utils/_subIssues/_subIssues.ts +function _subIssues(datasets) { + let issues; + if (datasets) { + for (const dataset of datasets) { + if (issues) { + issues.push(...dataset.issues); + } else { + issues = dataset.issues; + } + } + } + return issues; +} + +// src/schemas/union/union.ts +function union(options, message) { + return { + kind: "schema", + type: "union", + reference: union, + expects: _joinExpects( + options.map((option) => option.expects), + "|" + ), + async: false, + options, + message, + _run(dataset, config2) { + let validDataset; + let typedDatasets; + let untypedDatasets; + for (const schema of this.options) { + const optionDataset = schema._run( + { typed: false, value: dataset.value }, + config2 + ); + if (optionDataset.typed) { + if (optionDataset.issues) { + if (typedDatasets) { + typedDatasets.push(optionDataset); + } else { + typedDatasets = [optionDataset]; + } + } else { + validDataset = optionDataset; + break; + } + } else { + if (untypedDatasets) { + untypedDatasets.push(optionDataset); + } else { + untypedDatasets = [optionDataset]; + } + } + } + if (validDataset) { + return validDataset; + } + if (typedDatasets) { + if (typedDatasets.length === 1) { + return typedDatasets[0]; + } + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(typedDatasets) + }); + dataset.typed = true; + } else if (untypedDatasets?.length === 1) { + return untypedDatasets[0]; + } else { + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(untypedDatasets) + }); + } + return dataset; + } + }; +} + +// src/schemas/union/unionAsync.ts +function unionAsync(options, message) { + return { + kind: "schema", + type: "union", + reference: unionAsync, + expects: _joinExpects( + options.map((option) => option.expects), + "|" + ), + async: true, + options, + message, + async _run(dataset, config2) { + let validDataset; + let typedDatasets; + let untypedDatasets; + for (const schema of this.options) { + const optionDataset = await schema._run( + { typed: false, value: dataset.value }, + config2 + ); + if (optionDataset.typed) { + if (optionDataset.issues) { + if (typedDatasets) { + typedDatasets.push(optionDataset); + } else { + typedDatasets = [optionDataset]; + } + } else { + validDataset = optionDataset; + break; + } + } else { + if (untypedDatasets) { + untypedDatasets.push(optionDataset); + } else { + untypedDatasets = [optionDataset]; + } + } + } + if (validDataset) { + return validDataset; + } + if (typedDatasets) { + if (typedDatasets.length === 1) { + return typedDatasets[0]; + } + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(typedDatasets) + }); + dataset.typed = true; + } else if (untypedDatasets?.length === 1) { + return untypedDatasets[0]; + } else { + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(untypedDatasets) + }); + } + return dataset; + } + }; +} + +// src/schemas/unknown/unknown.ts +function unknown() { + return { + kind: "schema", + type: "unknown", + reference: unknown, + expects: "unknown", + async: false, + _run(dataset) { + dataset.typed = true; + return dataset; + } + }; +} + +// src/schemas/variant/utils/_discriminators/_discriminators.ts +function _discriminators(key, options, list = []) { + for (const schema of options) { + if (schema.type === "variant") { + _discriminators(key, schema.options, list); + } else { + list.push(schema.entries[key].expects); + } + } + return list; +} + +// src/schemas/variant/variant.ts +function variant(key, options, message) { + let expectedDiscriminators; + return { + kind: "schema", + type: "variant", + reference: variant, + expects: "Object", + async: false, + key, + options, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + const discriminator = input[this.key]; + if (this.key in input) { + let outputDataset; + for (const schema of this.options) { + if (schema.type === "variant" || !schema.entries[this.key]._run( + { typed: false, value: discriminator }, + config2 + ).issues) { + const optionDataset = schema._run( + { typed: false, value: input }, + config2 + ); + if (!optionDataset.issues) { + return optionDataset; + } + if (!outputDataset || !outputDataset.typed && optionDataset.typed) { + outputDataset = optionDataset; + } + } + } + if (outputDataset) { + return outputDataset; + } + } + if (!expectedDiscriminators) { + expectedDiscriminators = _joinExpects( + _discriminators(this.key, this.options), + "|" + ); + } + _addIssue(this, "type", dataset, config2, { + input: discriminator, + expected: expectedDiscriminators, + path: [ + { + type: "object", + origin: "value", + input, + key: this.key, + value: discriminator + } + ] + }); + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/variant/variantAsync.ts +function variantAsync(key, options, message) { + let expectedDiscriminators; + return { + kind: "schema", + type: "variant", + reference: variantAsync, + expects: "Object", + async: true, + key, + options, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + const discriminator = input[this.key]; + if (this.key in input) { + let outputDataset; + for (const schema of this.options) { + if (schema.type === "variant" || !(await schema.entries[this.key]._run( + { typed: false, value: discriminator }, + config2 + )).issues) { + const optionDataset = await schema._run( + { typed: false, value: input }, + config2 + ); + if (!optionDataset.issues) { + return optionDataset; + } + if (!outputDataset || !outputDataset.typed && optionDataset.typed) { + outputDataset = optionDataset; + } + } + } + if (outputDataset) { + return outputDataset; + } + } + if (!expectedDiscriminators) { + expectedDiscriminators = _joinExpects( + _discriminators(this.key, this.options), + "|" + ); + } + _addIssue(this, "type", dataset, config2, { + input: discriminator, + expected: expectedDiscriminators, + path: [ + { + type: "object", + origin: "value", + input, + key: this.key, + value: discriminator + } + ] + }); + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/void/void.ts +function void_(message) { + return { + kind: "schema", + type: "void", + reference: void_, + expects: "void", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/methods/keyof/keyof.ts +function keyof(schema, message) { + return picklist(Object.keys(schema.entries), message); +} + +// src/methods/omit/omit.ts +function omit(schema, keys) { + const entries = { + ...schema.entries + }; + for (const key of keys) { + delete entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/parse/parse.ts +function parse(schema, input, config2) { + const dataset = schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + if (dataset.issues) { + throw new ValiError(dataset.issues); + } + return dataset.value; +} + +// src/methods/parse/parseAsync.ts +async function parseAsync(schema, input, config2) { + const dataset = await schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + if (dataset.issues) { + throw new ValiError(dataset.issues); + } + return dataset.value; +} + +// src/methods/parser/parser.ts +function parser(schema, config2) { + const func = (input) => parse(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/parser/parserAsync.ts +function parserAsync(schema, config2) { + const func = (input) => parseAsync(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/partial/partial.ts +function partial(schema, keys) { + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? optional(schema.entries[key]) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/partial/partialAsync.ts +function partialAsync(schema, keys) { + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? optionalAsync(schema.entries[key]) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/pick/pick.ts +function pick(schema, keys) { + const entries = {}; + for (const key of keys) { + entries[key] = schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/pipe/pipe.ts +function pipe(...pipe2) { + return { + ...pipe2[0], + pipe: pipe2, + _run(dataset, config2) { + for (const item of pipe2) { + if (item.kind !== "metadata") { + if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { + dataset.typed = false; + break; + } + if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) { + dataset = item._run(dataset, config2); + } + } + } + return dataset; + } + }; +} + +// src/methods/pipe/pipeAsync.ts +function pipeAsync(...pipe2) { + return { + ...pipe2[0], + pipe: pipe2, + async: true, + async _run(dataset, config2) { + for (const item of pipe2) { + if (item.kind !== "metadata") { + if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { + dataset.typed = false; + break; + } + if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) { + dataset = await item._run(dataset, config2); + } + } + } + return dataset; + } + }; +} + +// src/methods/required/required.ts +function required(schema, arg2, arg3) { + const keys = Array.isArray(arg2) ? arg2 : void 0; + const message = Array.isArray(arg2) ? arg3 : arg2; + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? nonOptional(schema.entries[key], message) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/required/requiredAsync.ts +function requiredAsync(schema, arg2, arg3) { + const keys = Array.isArray(arg2) ? arg2 : void 0; + const message = Array.isArray(arg2) ? arg3 : arg2; + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? nonOptionalAsync(schema.entries[key], message) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/safeParse/safeParse.ts +function safeParse(schema, input, config2) { + const dataset = schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + return { + typed: dataset.typed, + success: !dataset.issues, + output: dataset.value, + issues: dataset.issues + }; +} + +// src/methods/safeParse/safeParseAsync.ts +async function safeParseAsync(schema, input, config2) { + const dataset = await schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + return { + typed: dataset.typed, + success: !dataset.issues, + output: dataset.value, + issues: dataset.issues + }; +} + +// src/methods/safeParser/safeParser.ts +function safeParser(schema, config2) { + const func = (input) => safeParse(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/safeParser/safeParserAsync.ts +function safeParserAsync(schema, config2) { + const func = (input) => safeParseAsync(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/unwrap/unwrap.ts +function unwrap(schema) { + return schema.wrapped; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BASE64_REGEX, + BIC_REGEX, + CUID2_REGEX, + DECIMAL_REGEX, + EMAIL_REGEX, + EMOJI_REGEX, + HEXADECIMAL_REGEX, + HEX_COLOR_REGEX, + IMEI_REGEX, + IPV4_REGEX, + IPV6_REGEX, + IP_REGEX, + ISO_DATE_REGEX, + ISO_DATE_TIME_REGEX, + ISO_TIMESTAMP_REGEX, + ISO_TIME_REGEX, + ISO_TIME_SECOND_REGEX, + ISO_WEEK_REGEX, + MAC48_REGEX, + MAC64_REGEX, + MAC_REGEX, + OCTAL_REGEX, + ULID_REGEX, + UUID_REGEX, + ValiError, + _addIssue, + _isLuhnAlgo, + _isValidObjectKey, + _joinExpects, + _stringify, + any, + array, + arrayAsync, + awaitAsync, + base64, + bic, + bigint, + blob, + boolean, + brand, + bytes, + check, + checkAsync, + checkItems, + config, + creditCard, + cuid2, + custom, + customAsync, + date, + decimal, + deleteGlobalConfig, + deleteGlobalMessage, + deleteSchemaMessage, + deleteSpecificMessage, + description, + email, + emoji, + empty, + endsWith, + entriesFromList, + enum: null, + enum_, + everyItem, + excludes, + fallback, + fallbackAsync, + file, + filterItems, + findItem, + finite, + flatten, + forward, + forwardAsync, + function: null, + function_, + getDefault, + getDefaults, + getDefaultsAsync, + getDotPath, + getFallback, + getFallbacks, + getFallbacksAsync, + getGlobalConfig, + getGlobalMessage, + getSchemaMessage, + getSpecificMessage, + hash, + hexColor, + hexadecimal, + imei, + includes, + instance, + integer, + intersect, + intersectAsync, + ip, + ipv4, + ipv6, + is, + isOfKind, + isOfType, + isValiError, + isoDate, + isoDateTime, + isoTime, + isoTimeSecond, + isoTimestamp, + isoWeek, + keyof, + lazy, + lazyAsync, + length, + literal, + looseObject, + looseObjectAsync, + looseTuple, + looseTupleAsync, + mac, + mac48, + mac64, + map, + mapAsync, + mapItems, + maxBytes, + maxLength, + maxSize, + maxValue, + mimeType, + minBytes, + minLength, + minSize, + minValue, + multipleOf, + nan, + never, + nonEmpty, + nonNullable, + nonNullableAsync, + nonNullish, + nonNullishAsync, + nonOptional, + nonOptionalAsync, + normalize, + notBytes, + notLength, + notSize, + notValue, + null: null, + null_, + nullable, + nullableAsync, + nullish, + nullishAsync, + number, + object, + objectAsync, + objectWithRest, + objectWithRestAsync, + octal, + omit, + optional, + optionalAsync, + parse, + parseAsync, + parser, + parserAsync, + partial, + partialAsync, + partialCheck, + partialCheckAsync, + pick, + picklist, + pipe, + pipeAsync, + promise, + rawCheck, + rawCheckAsync, + rawTransform, + rawTransformAsync, + readonly, + record, + recordAsync, + reduceItems, + regex, + required, + requiredAsync, + safeInteger, + safeParse, + safeParseAsync, + safeParser, + safeParserAsync, + set, + setAsync, + setGlobalConfig, + setGlobalMessage, + setSchemaMessage, + setSpecificMessage, + size, + someItem, + sortItems, + startsWith, + strictObject, + strictObjectAsync, + strictTuple, + strictTupleAsync, + string, + symbol, + toLowerCase, + toMaxValue, + toMinValue, + toUpperCase, + transform, + transformAsync, + trim, + trimEnd, + trimStart, + tuple, + tupleAsync, + tupleWithRest, + tupleWithRestAsync, + ulid, + undefined, + undefined_, + union, + unionAsync, + unknown, + unwrap, + url, + uuid, + value, + variant, + variantAsync, + void: null, + void_ +}); diff --git a/src/libMPC/node_modules/valibot/dist/index.d.cts b/src/libMPC/node_modules/valibot/dist/index.d.cts new file mode 100644 index 0000000..0b97e53 --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.d.cts @@ -0,0 +1,12416 @@ +/** + * Any schema type. + */ +interface AnySchema extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'any'; + /** + * The schema reference. + */ + readonly reference: typeof any; + /** + * The expected property. + */ + readonly expects: 'any'; +} +/** + * Creates an any schema. + * + * Hint: This schema function exists only for completeness and is not + * recommended in practice. Instead, `unknown` should be used to accept + * unknown data. + * + * @returns An any schema. + */ +declare function any(): AnySchema; + +/** + * Array issue type. + */ +interface ArrayIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'array'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Array schema type. + */ +interface ArraySchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema[], InferOutput[], ArrayIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'array'; + /** + * The schema reference. + */ + readonly reference: typeof array; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The array item schema. + */ + readonly item: TItem; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an array schema. + * + * @param item The item schema. + * + * @returns An array schema. + */ +declare function array>>(item: TItem): ArraySchema; +/** + * Creates an array schema. + * + * @param item The item schema. + * @param message The error message. + * + * @returns An array schema. + */ +declare function array>, const TMessage extends ErrorMessage | undefined>(item: TItem, message: TMessage): ArraySchema; + +/** + * Array schema type. + */ +interface ArraySchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync[], InferOutput[], ArrayIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'array'; + /** + * The schema reference. + */ + readonly reference: typeof arrayAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The array item schema. + */ + readonly item: TItem; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an array schema. + * + * @param item The item schema. + * + * @returns An array schema. + */ +declare function arrayAsync> | BaseSchemaAsync>>(item: TItem): ArraySchemaAsync; +/** + * Creates an array schema. + * + * @param item The item schema. + * @param message The error message. + * + * @returns An array schema. + */ +declare function arrayAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(item: TItem, message: TMessage): ArraySchemaAsync; + +/** + * Bigint issue type. + */ +interface BigintIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'bigint'; + /** + * The expected property. + */ + readonly expected: 'bigint'; +} +/** + * Bigint schema type. + */ +interface BigintSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'bigint'; + /** + * The schema reference. + */ + readonly reference: typeof bigint; + /** + * The expected property. + */ + readonly expects: 'bigint'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a bigint schema. + * + * @returns A bigint schema. + */ +declare function bigint(): BigintSchema; +/** + * Creates a bigint schema. + * + * @param message The error message. + * + * @returns A bigint schema. + */ +declare function bigint | undefined>(message: TMessage): BigintSchema; + +/** + * Blob issue type. + */ +interface BlobIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'blob'; + /** + * The expected property. + */ + readonly expected: 'Blob'; +} +/** + * Blob schema type. + */ +interface BlobSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'blob'; + /** + * The schema reference. + */ + readonly reference: typeof blob; + /** + * The expected property. + */ + readonly expects: 'Blob'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a blob schema. + * + * @returns A blob schema. + */ +declare function blob(): BlobSchema; +/** + * Creates a blob schema. + * + * @param message The error message. + * + * @returns A blob schema. + */ +declare function blob | undefined>(message: TMessage): BlobSchema; + +/** + * Boolean issue type. + */ +interface BooleanIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'boolean'; + /** + * The expected property. + */ + readonly expected: 'boolean'; +} +/** + * Boolean schema type. + */ +interface BooleanSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'boolean'; + /** + * The schema reference. + */ + readonly reference: typeof boolean; + /** + * The expected property. + */ + readonly expects: 'boolean'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a boolean schema. + * + * @returns A boolean schema. + */ +declare function boolean(): BooleanSchema; +/** + * Creates a boolean schema. + * + * @param message The error message. + * + * @returns A boolean schema. + */ +declare function boolean | undefined>(message: TMessage): BooleanSchema; + +/** + * Custom issue type. + */ +interface CustomIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'custom'; + /** + * The expected property. + */ + readonly expected: 'unknown'; +} + +/** + * Check type. + */ +type Check = (input: unknown) => boolean; +/** + * Custom schema type. + */ +interface CustomSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'custom'; + /** + * The schema reference. + */ + readonly reference: typeof custom; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The type check function. + */ + readonly check: Check; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a custom schema. + * + * @param check The type check function. + * + * @returns A custom schema. + */ +declare function custom(check: Check): CustomSchema; +/** + * Creates a custom schema. + * + * @param check The type check function. + * @param message The error message. + * + * @returns A custom schema. + */ +declare function custom | undefined = ErrorMessage | undefined>(check: Check, message: TMessage): CustomSchema; + +/** + * Check async type. + */ +type CheckAsync = (input: unknown) => MaybePromise; +/** + * Custom schema async type. + */ +interface CustomSchemaAsync | undefined> extends BaseSchemaAsync { + /** + * The schema type. + */ + readonly type: 'custom'; + /** + * The schema reference. + */ + readonly reference: typeof customAsync; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The type check function. + */ + readonly check: CheckAsync; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a custom schema. + * + * @param check The type check function. + * + * @returns A custom schema. + */ +declare function customAsync(check: CheckAsync): CustomSchemaAsync; +/** + * Creates a custom schema. + * + * @param check The type check function. + * @param message The error message. + * + * @returns A custom schema. + */ +declare function customAsync | undefined = ErrorMessage | undefined>(check: CheckAsync, message: TMessage): CustomSchemaAsync; + +/** + * Date issue type. + */ +interface DateIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'date'; + /** + * The expected property. + */ + readonly expected: 'Date'; +} +/** + * Date schema type. + */ +interface DateSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'date'; + /** + * The schema reference. + */ + readonly reference: typeof date; + /** + * The expected property. + */ + readonly expects: 'Date'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a date schema. + * + * @returns A date schema. + */ +declare function date(): DateSchema; +/** + * Creates a date schema. + * + * @param message The error message. + * + * @returns A date schema. + */ +declare function date | undefined>(message: TMessage): DateSchema; + +/** + * Enum type. + */ +interface Enum { + [key: string]: string | number; +} +/** + * Enum issue type. + */ +interface EnumIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'enum'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Enum schema type. + */ +interface EnumSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'enum'; + /** + * The schema reference. + */ + readonly reference: typeof enum_; + /** + * The enum object. + */ + readonly enum: TEnum; + /** + * The enum options. + */ + readonly options: TEnum[keyof TEnum][]; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an enum schema. + * + * @param enum__ The enum object. + * + * @returns An enum schema. + */ +declare function enum_(enum__: TEnum): EnumSchema; +/** + * Creates an enum schema. + * + * @param enum__ The enum object. + * @param message The error message. + * + * @returns An enum schema. + */ +declare function enum_ | undefined>(enum__: TEnum, message: TMessage): EnumSchema; + +/** + * File issue type. + */ +interface FileIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'file'; + /** + * The expected property. + */ + readonly expected: 'File'; +} +/** + * File schema type. + */ +interface FileSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'file'; + /** + * The schema reference. + */ + readonly reference: typeof file; + /** + * The expected property. + */ + readonly expects: 'File'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a file schema. + * + * @returns A file schema. + */ +declare function file(): FileSchema; +/** + * Creates a file schema. + * + * @param message The error message. + * + * @returns A file schema. + */ +declare function file | undefined>(message: TMessage): FileSchema; + +/** + * Function issue type. + */ +interface FunctionIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'function'; + /** + * The expected property. + */ + readonly expected: 'Function'; +} +/** + * Function schema type. + */ +interface FunctionSchema | undefined> extends BaseSchema<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown, FunctionIssue> { + /** + * The schema type. + */ + readonly type: 'function'; + /** + * The schema reference. + */ + readonly reference: typeof function_; + /** + * The expected property. + */ + readonly expects: 'Function'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a function schema. + * + * @returns A function schema. + */ +declare function function_(): FunctionSchema; +/** + * Creates a function schema. + * + * @param message The error message. + * + * @returns A function schema. + */ +declare function function_ | undefined>(message: TMessage): FunctionSchema; + +/** + * Class type. + */ +type Class = new (...args: any[]) => any; +/** + * Instance issue type. + */ +interface InstanceIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'instance'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Instance schema type. + */ +interface InstanceSchema | undefined> extends BaseSchema, InstanceType, InstanceIssue> { + /** + * The schema type. + */ + readonly type: 'instance'; + /** + * The schema reference. + */ + readonly reference: typeof instance; + /** + * The class of the instance. + */ + readonly class: TClass; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an instance schema. + * + * @param class_ The class of the instance. + * + * @returns An instance schema. + */ +declare function instance(class_: TClass): InstanceSchema; +/** + * Creates an instance schema. + * + * @param class_ The class of the instance. + * @param message The error message. + * + * @returns An instance schema. + */ +declare function instance | undefined>(class_: TClass, message: TMessage): InstanceSchema; + +/** + * Intersect issue type. + */ +interface IntersectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'intersect'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Intersect options type. + */ +type IntersectOptions = MaybeReadonly>[]>; +/** + * Intersect options async type. + */ +type IntersectOptionsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Infer option type. + */ +type InferOption = BaseSchema> | BaseSchemaAsync>; +/** + * Infer intersect input type. + */ +type InferIntersectInput = TOptions extends readonly [ + InferOption, + ...infer TRest +] ? TRest extends readonly [ + InferOption, + ...InferOption[] +] ? TInput & InferIntersectInput : TInput : never; +/** + * Infer intersect output type. + */ +type InferIntersectOutput = TOptions extends readonly [ + InferOption, + ...infer TRest +] ? TRest extends readonly [ + InferOption, + ...InferOption[] +] ? TOutput & InferIntersectOutput : TOutput : never; + +/** + * Intersect schema type. + */ +interface IntersectSchema | undefined> extends BaseSchema, InferIntersectOutput, IntersectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'intersect'; + /** + * The schema reference. + */ + readonly reference: typeof intersect; + /** + * The intersect options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * + * @returns An intersect schema. + */ +declare function intersect(options: TOptions): IntersectSchema; +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * @param message The error message. + * + * @returns An intersect schema. + */ +declare function intersect | undefined>(options: TOptions, message: TMessage): IntersectSchema; + +/** + * Intersect schema async type. + */ +interface IntersectSchemaAsync | undefined> extends BaseSchemaAsync, InferIntersectOutput, IntersectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'intersect'; + /** + * The schema reference. + */ + readonly reference: typeof intersectAsync; + /** + * The intersect options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * + * @returns An intersect schema. + */ +declare function intersectAsync(options: TOptions): IntersectSchemaAsync; +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * @param message The error message. + * + * @returns An intersect schema. + */ +declare function intersectAsync | undefined>(options: TOptions, message: TMessage): IntersectSchemaAsync; + +/** + * Lazy schema type. + */ +interface LazySchema>> extends BaseSchema, InferOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'lazy'; + /** + * The schema reference. + */ + readonly reference: typeof lazy; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The schema getter. + */ + readonly getter: (input: unknown) => TWrapped; +} +/** + * Creates a lazy schema. + * + * @param getter The schema getter. + * + * @returns A lazy schema. + */ +declare function lazy>>(getter: (input: unknown) => TWrapped): LazySchema; + +/** + * Lazy schema async type. + */ +interface LazySchemaAsync> | BaseSchemaAsync>> extends BaseSchemaAsync, InferOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'lazy'; + /** + * The schema reference. + */ + readonly reference: typeof lazyAsync; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The schema getter. + */ + readonly getter: (input: unknown) => MaybePromise; +} +/** + * Creates a lazy schema. + * + * @param getter The schema getter. + * + * @returns A lazy schema. + */ +declare function lazyAsync> | BaseSchemaAsync>>(getter: (input: unknown) => MaybePromise): LazySchemaAsync; + +/** + * Literal type. + */ +type Literal = bigint | boolean | number | string | symbol; +/** + * Literal issue type. + */ +interface LiteralIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'literal'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Literal schema type. + */ +interface LiteralSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'literal'; + /** + * The schema reference. + */ + readonly reference: typeof literal; + /** + * The literal value. + */ + readonly literal: TLiteral; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a literal schema. + * + * @param literal_ The literal value. + * + * @returns A literal schema. + */ +declare function literal(literal_: TLiteral): LiteralSchema; +/** + * Creates a literal schema. + * + * @param literal_ The literal value. + * @param message The error message. + * + * @returns A literal schema. + */ +declare function literal | undefined>(literal_: TLiteral, message: TMessage): LiteralSchema; + +/** + * Loose object issue type. + */ +interface LooseObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'loose_object'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Loose object schema type. + */ +interface LooseObjectSchema | undefined> extends BaseSchema & { + [key: string]: unknown; +}, InferObjectOutput & { + [key: string]: unknown; +}, LooseObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'loose_object'; + /** + * The schema reference. + */ + readonly reference: typeof looseObject; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * + * @returns A loose object schema. + */ +declare function looseObject(entries: TEntries): LooseObjectSchema; +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A loose object schema. + */ +declare function looseObject | undefined>(entries: TEntries, message: TMessage): LooseObjectSchema; + +/** + * Object schema async type. + */ +interface LooseObjectSchemaAsync | undefined> extends BaseSchemaAsync & { + [key: string]: unknown; +}, InferObjectOutput & { + [key: string]: unknown; +}, LooseObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'loose_object'; + /** + * The schema reference. + */ + readonly reference: typeof looseObjectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * + * @returns A loose object schema. + */ +declare function looseObjectAsync(entries: TEntries): LooseObjectSchemaAsync; +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A loose object schema. + */ +declare function looseObjectAsync | undefined>(entries: TEntries, message: TMessage): LooseObjectSchemaAsync; + +/** + * Loose tuple issue type. + */ +interface LooseTupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'loose_tuple'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Loose tuple schema type. + */ +interface LooseTupleSchema | undefined> extends BaseSchema<[ + ...InferTupleInput, + ...unknown[] +], [ + ...InferTupleOutput, + ...unknown[] +], LooseTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'loose_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof looseTuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * + * @returns A loose tuple schema. + */ +declare function looseTuple(items: TItems): LooseTupleSchema; +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A loose tuple schema. + */ +declare function looseTuple | undefined>(items: TItems, message: TMessage): LooseTupleSchema; + +/** + * Loose tuple schema async type. + */ +interface LooseTupleSchemaAsync | undefined> extends BaseSchemaAsync<[ + ...InferTupleInput, + ...unknown[] +], [ + ...InferTupleOutput, + ...unknown[] +], LooseTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'loose_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof looseTupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * + * @returns A loose tuple schema. + */ +declare function looseTupleAsync(items: TItems): LooseTupleSchemaAsync; +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A loose tuple schema. + */ +declare function looseTupleAsync | undefined>(items: TItems, message: TMessage): LooseTupleSchemaAsync; + +/** + * Map issue type. + */ +interface MapIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'map'; + /** + * The expected property. + */ + readonly expected: 'Map'; +} +/** + * Infer map input type. + */ +type InferMapInput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Map, InferInput>; +/** + * Infer map output type. + */ +type InferMapOutput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Map, InferOutput>; + +/** + * Map schema type. + */ +interface MapSchema>, TValue extends BaseSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferMapOutput, MapIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'map'; + /** + * The schema reference. + */ + readonly reference: typeof map; + /** + * The expected property. + */ + readonly expects: 'Map'; + /** + * The map key schema. + */ + readonly key: TKey; + /** + * The map value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A map schema. + */ +declare function map>, const TValue extends BaseSchema>>(key: TKey, value: TValue): MapSchema; +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A map schema. + */ +declare function map>, const TValue extends BaseSchema>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): MapSchema; + +/** + * Map schema async type. + */ +interface MapSchemaAsync> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferMapOutput, MapIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'map'; + /** + * The schema reference. + */ + readonly reference: typeof mapAsync; + /** + * The expected property. + */ + readonly expects: 'Map'; + /** + * The map key schema. + */ + readonly key: TKey; + /** + * The map value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A map schema. + */ +declare function mapAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>>(key: TKey, value: TValue): MapSchemaAsync; +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A map schema. + */ +declare function mapAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): MapSchemaAsync; + +/** + * NaN issue type. + */ +interface NanIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'nan'; + /** + * The expected property. + */ + readonly expected: 'NaN'; +} +/** + * NaN schema type. + */ +interface NanSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'nan'; + /** + * The schema reference. + */ + readonly reference: typeof nan; + /** + * The expected property. + */ + readonly expects: 'NaN'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a NaN schema. + * + * @returns A NaN schema. + */ +declare function nan(): NanSchema; +/** + * Creates a NaN schema. + * + * @param message The error message. + * + * @returns A NaN schema. + */ +declare function nan | undefined>(message: TMessage): NanSchema; + +/** + * Never issue type. + */ +interface NeverIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'never'; + /** + * The expected property. + */ + readonly expected: 'never'; +} +/** + * Never schema type. + */ +interface NeverSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'never'; + /** + * The schema reference. + */ + readonly reference: typeof never; + /** + * The expected property. + */ + readonly expects: 'never'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a never schema. + * + * @returns A never schema. + */ +declare function never(): NeverSchema; +/** + * Creates a never schema. + * + * @param message The error message. + * + * @returns A never schema. + */ +declare function never | undefined>(message: TMessage): NeverSchema; + +/** + * Union issue type. + */ +interface UnionIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'union'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The sub issues. + */ + readonly issues?: [TSubIssue, ...TSubIssue[]]; +} + +/** + * Union options type. + */ +type UnionOptions = MaybeReadonly>[]>; +/** + * Union schema type. + */ +interface UnionSchema>> | undefined> extends BaseSchema, InferOutput, UnionIssue> | InferIssue> { + /** + * The schema type. + */ + readonly type: 'union'; + /** + * The schema reference. + */ + readonly reference: typeof union; + /** + * The union options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an union schema. + * + * @param options The union options. + * + * @returns An union schema. + */ +declare function union(options: TOptions): UnionSchema; +/** + * Creates an union schema. + * + * @param options The union options. + * @param message The error message. + * + * @returns An union schema. + */ +declare function union>> | undefined>(options: TOptions, message: TMessage): UnionSchema; + +/** + * Union options async type. + */ +type UnionOptionsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Union schema async type. + */ +interface UnionSchemaAsync>> | undefined> extends BaseSchemaAsync, InferOutput, UnionIssue> | InferIssue> { + /** + * The schema type. + */ + readonly type: 'union'; + /** + * The schema reference. + */ + readonly reference: typeof unionAsync; + /** + * The union options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an union schema. + * + * @param options The union options. + * + * @returns An union schema. + */ +declare function unionAsync(options: TOptions): UnionSchemaAsync; +/** + * Creates an union schema. + * + * @param options The union options. + * @param message The error message. + * + * @returns An union schema. + */ +declare function unionAsync>> | undefined>(options: TOptions, message: TMessage): UnionSchemaAsync; + +/** + * Non nullable issue type. + */ +interface NonNullableIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_nullable'; + /** + * The expected property. + */ + readonly expected: '!null'; +} +/** + * Infer non nullable input type. + */ +type InferNonNullableInput> | BaseSchemaAsync>> = NonNullable$1>; +/** + * Infer non nullable output type. + */ +type InferNonNullableOutput> | BaseSchemaAsync>> = NonNullable$1>; +/** + * Infer non nullable issue type. + */ +type InferNonNullableIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'null' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'null'; +}>; + +/** + * Non nullable schema type. + */ +interface NonNullableSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonNullableOutput, NonNullableIssue | InferNonNullableIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullable; + /** + * The expected property. + */ + readonly expects: '!null'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullable schema. + */ +declare function nonNullable>>(wrapped: TWrapped): NonNullableSchema; +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullable schema. + */ +declare function nonNullable>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullableSchema; + +/** + * Non nullable schema async type. + */ +interface NonNullableSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonNullableOutput, NonNullableIssue | InferNonNullableIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullableAsync; + /** + * The expected property. + */ + readonly expects: '!null'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullable schema. + */ +declare function nonNullableAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonNullableSchemaAsync; +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullable schema. + */ +declare function nonNullableAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullableSchemaAsync; + +/** + * Non nullish issue type. + */ +interface NonNullishIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_nullish'; + /** + * The expected property. + */ + readonly expected: '(!null & !undefined)'; +} +/** + * Infer non nullish input type. + */ +type InferNonNullishInput> | BaseSchemaAsync>> = NonNullish>; +/** + * Infer non nullish output type. + */ +type InferNonNullishOutput> | BaseSchemaAsync>> = NonNullish>; +/** + * Infer non nullish issue type. + */ +type InferNonNullishIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'null' | 'undefined' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'null' | 'undefined'; +}>; + +/** + * Non nullish schema type. + */ +interface NonNullishSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonNullishOutput, NonNullishIssue | InferNonNullishIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullish; + /** + * The expected property. + */ + readonly expects: '(!null & !undefined)'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullish schema. + */ +declare function nonNullish>>(wrapped: TWrapped): NonNullishSchema; +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullish schema. + */ +declare function nonNullish>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullishSchema; + +/** + * Non nullish schema async type. + */ +interface NonNullishSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonNullishOutput, NonNullishIssue | InferNonNullishIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullishAsync; + /** + * The expected property. + */ + readonly expects: '(!null & !undefined)'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullish schema. + */ +declare function nonNullishAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonNullishSchemaAsync; +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullish schema. + */ +declare function nonNullishAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullishSchemaAsync; + +/** + * Non optional issue type. + */ +interface NonOptionalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_optional'; + /** + * The expected property. + */ + readonly expected: '!undefined'; +} +/** + * Infer non optional input type. + */ +type InferNonOptionalInput> | BaseSchemaAsync>> = NonOptional>; +/** + * Infer non optional output type. + */ +type InferNonOptionalOutput> | BaseSchemaAsync>> = NonOptional>; +/** + * Infer non optional issue type. + */ +type InferNonOptionalIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'undefined' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'undefined'; +}>; + +/** + * Non optional schema type. + */ +interface NonOptionalSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonOptionalOutput, NonOptionalIssue | InferNonOptionalIssue> { + /** + * The schema type. + */ + readonly type: 'non_optional'; + /** + * The schema reference. + */ + readonly reference: typeof nonOptional; + /** + * The expected property. + */ + readonly expects: '!undefined'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non optional schema. + */ +declare function nonOptional>>(wrapped: TWrapped): NonOptionalSchema; +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non optional schema. + */ +declare function nonOptional>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonOptionalSchema; + +/** + * Non optional schema async type. + */ +interface NonOptionalSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonOptionalOutput, NonOptionalIssue | InferNonOptionalIssue> { + /** + * The schema type. + */ + readonly type: 'non_optional'; + /** + * The schema reference. + */ + readonly reference: typeof nonOptionalAsync; + /** + * The expected property. + */ + readonly expects: '!undefined'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non optional schema. + */ +declare function nonOptionalAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonOptionalSchemaAsync; +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non optional schema. + */ +declare function nonOptionalAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonOptionalSchemaAsync; + +/** + * Null issue type. + */ +interface NullIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'null'; + /** + * The expected property. + */ + readonly expected: 'null'; +} +/** + * Null schema type. + */ +interface NullSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'null'; + /** + * The schema reference. + */ + readonly reference: typeof null_; + /** + * The expected property. + */ + readonly expects: 'null'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a null schema. + * + * @returns A null schema. + */ +declare function null_(): NullSchema; +/** + * Creates a null schema. + * + * @param message The error message. + * + * @returns A null schema. + */ +declare function null_ | undefined>(message: TMessage): NullSchema; + +/** + * Infer nullable output type. + */ +type InferNullableOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | null : // FIXME: For schemas that transform the input to `null`, this +NonNullable$1> | Extract, null>; + +/** + * Nullable schema type. + */ +interface NullableSchema>, TDefault extends Default> extends BaseSchema | null, InferNullableOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nullable; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullable schema. + */ +declare function nullable>>(wrapped: TWrapped): NullableSchema; +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullable schema. + */ +declare function nullable>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): NullableSchema; + +/** + * Nullable schema async type. + */ +interface NullableSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | null, InferNullableOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nullableAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullable schema. + */ +declare function nullableAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NullableSchemaAsync; +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullable schema. + */ +declare function nullableAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): NullableSchemaAsync; + +/** + * Infer nullish output type. + */ +type InferNullishOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | null | undefined : NonNullish> | Extract, null | undefined>; + +/** + * Nullish schema type. + */ +interface NullishSchema>, TDefault extends Default> extends BaseSchema | null | undefined, InferNullishOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nullish; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullish schema. + */ +declare function nullish>>(wrapped: TWrapped): NullishSchema; +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullish schema. + */ +declare function nullish>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): NullishSchema; + +/** + * Nullish schema async type. + */ +interface NullishSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | null | undefined, InferNullishOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nullishAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullish schema. + */ +declare function nullishAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NullishSchemaAsync; +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullish schema. + */ +declare function nullishAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): NullishSchemaAsync; + +/** + * Number issue type. + */ +interface NumberIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'number'; + /** + * The expected property. + */ + readonly expected: 'number'; +} +/** + * Number schema type. + */ +interface NumberSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'number'; + /** + * The schema reference. + */ + readonly reference: typeof number; + /** + * The expected property. + */ + readonly expects: 'number'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a number schema. + * + * @returns A number schema. + */ +declare function number(): NumberSchema; +/** + * Creates a number schema. + * + * @param message The error message. + * + * @returns A number schema. + */ +declare function number | undefined>(message: TMessage): NumberSchema; + +/** + * Object issue type. + */ +interface ObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'object'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Object schema type. + */ +interface ObjectSchema | undefined> extends BaseSchema, InferObjectOutput, ObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'object'; + /** + * The schema reference. + */ + readonly reference: typeof object; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObject`. To + * return an issue for unknown entries, use `strictObject`. To include and + * validate unknown entries, use `objectWithRest`. + * + * @param entries The entries schema. + * + * @returns An object schema. + */ +declare function object(entries: TEntries): ObjectSchema; +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObject`. To + * return an issue for unknown entries, use `strictObject`. To include and + * validate unknown entries, use `objectWithRest`. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns An object schema. + */ +declare function object | undefined>(entries: TEntries, message: TMessage): ObjectSchema; + +/** + * Object schema async type. + */ +interface ObjectSchemaAsync | undefined> extends BaseSchemaAsync, InferObjectOutput, ObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'object'; + /** + * The schema reference. + */ + readonly reference: typeof objectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObjectAsync`. To + * return an issue for unknown entries, use `strictObjectAsync`. To include and + * validate unknown entries, use `objectWithRestAsync`. + * + * @param entries The entries schema. + * + * @returns An object schema. + */ +declare function objectAsync(entries: TEntries): ObjectSchemaAsync; +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObjectAsync`. To + * return an issue for unknown entries, use `strictObjectAsync`. To include and + * validate unknown entries, use `objectWithRestAsync`. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns An object schema. + */ +declare function objectAsync | undefined>(entries: TEntries, message: TMessage): ObjectSchemaAsync; + +/** + * Object with rest issue type. + */ +interface ObjectWithRestIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'object_with_rest'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Object with rest schema type. + */ +interface ObjectWithRestSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema & { + [key: string]: InferInput; +}, InferObjectOutput & { + [key: string]: InferOutput; +}, ObjectWithRestIssue | InferObjectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'object_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof objectWithRest; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * + * @returns An object with rest schema. + */ +declare function objectWithRest>>(entries: TEntries, rest: TRest): ObjectWithRestSchema; +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns An object with rest schema. + */ +declare function objectWithRest>, const TMessage extends ErrorMessage | undefined>(entries: TEntries, rest: TRest, message: TMessage): ObjectWithRestSchema; + +/** + * Object schema async type. + */ +interface ObjectWithRestSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync & { + [key: string]: InferInput; +}, InferObjectOutput & { + [key: string]: InferOutput; +}, ObjectWithRestIssue | InferObjectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'object_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof objectWithRestAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * + * @returns An object with rest schema. + */ +declare function objectWithRestAsync> | BaseSchemaAsync>>(entries: TEntries, rest: TRest): ObjectWithRestSchemaAsync; +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns An object with rest schema. + */ +declare function objectWithRestAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(entries: TEntries, rest: TRest, message: TMessage): ObjectWithRestSchemaAsync; + +/** + * Infer optional output type. + */ +type InferOptionalOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | undefined : NonOptional> | Extract, undefined>; + +/** + * Optional schema type. + */ +interface OptionalSchema>, TDefault extends Default> extends BaseSchema | undefined, InferOptionalOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'optional'; + /** + * The schema reference. + */ + readonly reference: typeof optional; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A optional schema. + */ +declare function optional>>(wrapped: TWrapped): OptionalSchema; +/** + * Creates a optional schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A optional schema. + */ +declare function optional>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): OptionalSchema; + +/** + * Optional schema async type. + */ +interface OptionalSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | undefined, InferOptionalOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'optional'; + /** + * The schema reference. + */ + readonly reference: typeof optionalAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates an optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns An optional schema. + */ +declare function optionalAsync> | BaseSchemaAsync>>(wrapped: TWrapped): OptionalSchemaAsync; +/** + * Creates an optional schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns An optional schema. + */ +declare function optionalAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): OptionalSchemaAsync; + +/** + * Picklist options type. + */ +type PicklistOptions = MaybeReadonly<(string | number | bigint)[]>; +/** + * Picklist issue type. + */ +interface PicklistIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'picklist'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Picklist schema type. + */ +interface PicklistSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'picklist'; + /** + * The schema reference. + */ + readonly reference: typeof picklist; + /** + * The picklist options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a picklist schema. + * + * @param options The picklist options. + * + * @returns A picklist schema. + */ +declare function picklist(options: TOptions): PicklistSchema; +/** + * Creates a picklist schema. + * + * @param options The picklist options. + * @param message The error message. + * + * @returns A picklist schema. + */ +declare function picklist | undefined>(options: TOptions, message: TMessage): PicklistSchema; + +/** + * Promise issue type. + */ +interface PromiseIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'promise'; + /** + * The expected property. + */ + readonly expected: 'Promise'; +} +/** + * Promise schema type. + */ +interface PromiseSchema | undefined> extends BaseSchema, Promise, PromiseIssue> { + /** + * The schema type. + */ + readonly type: 'promise'; + /** + * The schema reference. + */ + readonly reference: typeof promise; + /** + * The expected property. + */ + readonly expects: 'Promise'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a promise schema. + * + * @returns A promise schema. + */ +declare function promise(): PromiseSchema; +/** + * Creates a promise schema. + * + * @param message The error message. + * + * @returns A promise schema. + */ +declare function promise | undefined>(message: TMessage): PromiseSchema; + +/** + * Changes the local configuration of a schema. + * + * @param schema The schema to configure. + * @param config The parse configuration. + * + * @returns The configured schema. + */ +declare function config> | BaseSchemaAsync>>(schema: TSchema, config: Config>): TSchema; + +/** + * Fallback type. + */ +type Fallback>> = InferOutput | ((dataset?: Dataset, InferIssue>, config?: Config>) => InferOutput); +/** + * Schema with fallback type. + */ +type SchemaWithFallback>, TFallback extends Fallback> = TSchema & { + /** + * The fallback value. + */ + readonly fallback: TFallback; +}; +/** + * Returns a fallback value as output if the input does not match the schema. + * + * @param schema The schema to catch. + * @param fallback The fallback value. + * + * @returns The passed schema. + */ +declare function fallback>, const TFallback extends Fallback>(schema: TSchema, fallback: TFallback): SchemaWithFallback; + +/** + * Fallback async type. + */ +type FallbackAsync> | BaseSchemaAsync>> = InferOutput | ((dataset?: Dataset, InferIssue>, config?: Config>) => MaybePromise>); +/** + * Schema with fallback async type. + */ +type SchemaWithFallbackAsync> | BaseSchemaAsync>, TFallback extends FallbackAsync> = Omit & { + /** + * The fallback value. + */ + readonly fallback: TFallback; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>) => Promise, InferIssue>>; +}; +/** + * Returns a fallback value as output if the input does not match the schema. + * + * @param schema The schema to catch. + * @param fallback The fallback value. + * + * @returns The passed schema. + */ +declare function fallbackAsync> | BaseSchemaAsync>, const TFallback extends FallbackAsync>(schema: TSchema, fallback: TFallback): SchemaWithFallbackAsync; + +/** + * Flat errors type. + */ +type FlatErrors> | BaseSchemaAsync> | undefined> = Prettify<{ + /** + * The root errors. + * + * Hint: The error messages of issues without a path that belong to the root + * of the schema are added to this key. + */ + readonly root?: [string, ...string[]]; + /** + * The nested errors. + * + * Hint: The error messages of issues with a path that belong to the nested + * parts of the schema and can be converted to a dot path are added to this + * key. + */ + readonly nested?: Prettify> | BaseSchemaAsync> ? IssueDotPath : string, [ + string, + ...string[] + ]>>>>; + /** + * The other errors. + * + * Hint: Some issue paths, for example for complex data types like `Set` and + * `Map`, have no key or a key that cannot be converted to a dot path. These + * error messages are added to this key. + */ + readonly other?: [string, ...string[]]; +}>; +/** + * Flatten the error messages of issues. + * + * @param issues The list of issues. + * + * @returns A flat error object. + */ +declare function flatten(issues: [BaseIssue, ...BaseIssue[]]): FlatErrors; +/** + * Flatten the error messages of issues. + * + * @param issues The list of issues. + * + * @returns A flat error object. + */ +declare function flatten> | BaseSchemaAsync>>(issues: [InferIssue, ...InferIssue[]]): FlatErrors; + +/** + * Forwards the issues of the passed validation action. + * + * @param action The validation action. + * @param pathKeys The path keys. + * + * @returns The modified action. + */ +declare function forward | ArrayLike, TIssue extends BaseIssue>(action: BaseValidation, pathKeys: PathKeys): BaseValidation; + +/** + * Forwards the issues of the passed validation action. + * + * @param action The validation action. + * @param pathKeys The path keys. + * + * @returns The modified action. + */ +declare function forwardAsync | ArrayLike, TIssue extends BaseIssue>(action: BaseValidation | BaseValidationAsync, pathKeys: PathKeys): BaseValidationAsync; + +/** + * Infer default type. + */ +type InferDefault> | BaseSchemaAsync> | NullableSchema>, unknown> | NullableSchemaAsync> | BaseSchemaAsync>, unknown> | NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>> = TSchema extends NullableSchema>, infer TDefault> | NullableSchemaAsync> | BaseSchemaAsync>, infer TDefault> | NullishSchema>, infer TDefault> | NullishSchemaAsync> | BaseSchemaAsync>, infer TDefault> | OptionalSchema>, infer TDefault> | OptionalSchemaAsync> | BaseSchemaAsync>, infer TDefault> ? [TDefault] extends [never] ? undefined : TDefault extends () => MaybePromise> ? ReturnType : TDefault : undefined; +/** + * Returns the default value of the schema. + * + * @param schema The schema to get it from. + * @param dataset The input dataset if available. + * @param config The config if available. + * + * @returns The default value. + */ +declare function getDefault> | BaseSchemaAsync>>(schema: TSchema, dataset?: Dataset, config?: Config>): InferDefault; + +/** + * Infer defaults type. + */ +type InferDefaults> | BaseSchemaAsync>> = TSchema extends LooseObjectSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> ? { + -readonly [TKey in keyof TEntries]: InferDefaults; +} : TSchema extends LooseObjectSchemaAsync | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined> ? { + -readonly [TKey in keyof TEntries]: InferDefaults; +} : TSchema extends LooseTupleSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferDefaults; +} : TSchema extends LooseTupleSchemaAsync | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchemaAsync>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferDefaults; +} : Awaited>; + +/** + * Returns the default values of the schema. + * + * Hint: The difference to `getDefault` is that for object and tuple schemas + * this function recursively returns the default values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The default values. + */ +declare function getDefaults> | LooseObjectSchema | undefined> | LooseTupleSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined>>(schema: TSchema): InferDefaults; + +/** + * Returns the default values of the schema. + * + * Hint: The difference to `getDefault` is that for object and tuple schemas + * this function recursively returns the default values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The default values. + */ +declare function getDefaultsAsync> | BaseSchemaAsync> | LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> | TupleWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined>>(schema: TSchema): Promise>; + +/** + * Infer fallback type. + */ +type InferFallback> | BaseSchemaAsync>> = TSchema extends SchemaWithFallback>, infer TFallback> | SchemaWithFallbackAsync> | BaseSchemaAsync>, infer TFallback> ? TFallback extends InferOutput ? TFallback : TFallback extends () => MaybePromise> ? ReturnType : never : undefined; +/** + * Returns the fallback value of the schema. + * + * @param schema The schema to get it from. + * @param dataset The output dataset if available. + * @param config The config if available. + * + * @returns The fallback value. + */ +declare function getFallback> | BaseSchemaAsync>>(schema: TSchema, dataset?: Dataset, InferIssue>, config?: Config>): InferFallback; + +/** + * Infer fallbacks type. + */ +type InferFallbacks> | BaseSchemaAsync>> = TSchema extends LooseObjectSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> ? { + -readonly [TKey in keyof TEntries]: InferFallbacks; +} : TSchema extends LooseObjectSchemaAsync | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined> ? { + -readonly [TKey in keyof TEntries]: InferFallbacks; +} : TSchema extends LooseTupleSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferFallbacks; +} : TSchema extends LooseTupleSchemaAsync | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchemaAsync>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferFallbacks; +} : Awaited>; + +/** + * Returns the fallback values of the schema. + * + * Hint: The difference to `getFallback` is that for object and tuple schemas + * this function recursively returns the fallback values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The fallback values. + */ +declare function getFallbacks> | LooseObjectSchema | undefined> | LooseTupleSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined>>(schema: TSchema): InferFallbacks; + +/** + * Returns the fallback values of the schema. + * + * Hint: The difference to `getFallback` is that for object and tuple schemas + * this function recursively returns the fallback values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The fallback values. + */ +declare function getFallbacksAsync> | BaseSchemaAsync> | LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> | TupleWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined>>(schema: TSchema): Promise>; + +/** + * Checks if the input matches the scheme. By using a type predicate, this + * function can be used as a type guard. + * + * @param schema The schema to be used. + * @param input The input to be tested. + * + * @returns Whether the input matches the scheme. + */ +declare function is>>(schema: TSchema, input: unknown): input is InferInput; + +/** + * Schema type. + */ +type Schema$6 = LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>; +/** + * Force tuple type. + */ +type ForceTuple = T extends [string, ...string[]] ? T : []; +/** + * Object keys type. + */ +type ObjectKeys$1 = ForceTuple>; +/** + * Creates a picklist schema of object keys. + * + * @param schema The object schema. + * + * @returns A picklist schema. + */ +declare function keyof(schema: TSchema): PicklistSchema, undefined>; +/** + * Creates a picklist schema of object keys. + * + * @param schema The object schema. + * @param message The error message. + * + * @returns A picklist schema. + */ +declare function keyof | undefined>(schema: TSchema, message: TMessage): PicklistSchema, TMessage>; + +/** + * Schema type. + */ +type Schema$5 = NoPipe | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Schema with omit type. + */ +type SchemaWithOmit> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Dataset> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Promise> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that does not contain the + * selected entries. + * + * @param schema The schema to omit from. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function omit>(schema: TSchema, keys: TKeys): SchemaWithOmit; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parsed input. + */ +declare function parse>>(schema: TSchema, input: unknown, config?: Config>): InferOutput; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parsed input. + */ +declare function parseAsync> | BaseSchemaAsync>>(schema: TSchema, input: unknown, config?: Config>): Promise>; + +/** + * The parser type. + */ +interface Parser>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): InferOutput; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function parser>>(schema: TSchema): Parser; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function parser>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): Parser; + +/** + * The parser async type. + */ +interface ParserAsync> | BaseSchemaAsync>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): Promise>; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function parserAsync> | BaseSchemaAsync>>(schema: TSchema): ParserAsync; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function parserAsync> | BaseSchemaAsync>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): ParserAsync; + +/** + * Schema type. + */ +type Schema$4 = NoPipe | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined>>; +/** + * Partial entries type. + */ +type PartialEntries$1 = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? OptionalSchema : TEntries[TKey] : OptionalSchema; +}; +/** + * Schema with partial type. + */ +type SchemaWithPartial | undefined> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset>, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: InferIssue; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: unknown; + }, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: InferIssue; + }; +} : TSchema extends ObjectWithRestSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: InferOutput; + }, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as optional. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function partial(schema: TSchema): SchemaWithPartial; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as optional. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function partial>(schema: TSchema, keys: TKeys): SchemaWithPartial; + +/** + * Schema type. + */ +type Schema$3 = NoPipe | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Partial entries type. + */ +type PartialEntries = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? OptionalSchemaAsync : TEntries[TKey] : OptionalSchemaAsync; +}; +/** + * Schema with partial type. + */ +type SchemaWithPartialAsync | undefined> = TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise>, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: InferIssue; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: unknown; + }, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: InferOutput; + }, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as optional. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function partialAsync(schema: TSchema): SchemaWithPartialAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as optional. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function partialAsync>(schema: TSchema, keys: TKeys): SchemaWithPartialAsync; + +/** + * The schema type. + */ +type Schema$2 = NoPipe | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Schema with pick type. + */ +type SchemaWithPick> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Dataset> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Promise> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that contains only the selected + * entries. + * + * @param schema The schema to pick from. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function pick>(schema: TSchema, keys: TKeys): SchemaWithPick; + +/** + * Schema with pipe type. + */ +type SchemaWithPipe>, + ...PipeItem>[] +]> = Omit, '_run' | '_types'> & { + /** + * The pipe items. + */ + readonly pipe: TPipe; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>>) => Dataset>, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferInput>; + readonly output: InferOutput>; + readonly issue: InferIssue; + }; +}; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5, TItem6]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * @param item19 The nineteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue>, const TItem19 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue>, item19: TItem19 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18, + TItem19 +]>; + +/** + * Schema with pipe async type. + */ +type SchemaWithPipeAsync> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] +]> = Omit, 'async' | '_run' | '_types'> & { + /** + * The pipe items. + */ + readonly pipe: TPipe; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>>) => Promise>, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferInput>; + readonly output: InferOutput>; + readonly issue: InferIssue; + }; +}; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3, TItem4]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * @param item19 The nineteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem19 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item19: TItem19 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18, + TItem19 +]>; + +/** + * Schema type. + */ +type Schema$1 = NoPipe | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined>>; +/** + * Required entries type. + */ +type RequiredEntries$1 | undefined> = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? NonOptionalSchema : TEntries[TKey] : NonOptionalSchema; +}; +/** + * Schema with required type. + */ +type SchemaWithRequired | undefined, TMessage extends ErrorMessage | undefined> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset>, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: unknown; + }, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends ObjectWithRestSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: InferOutput; + }, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function required(schema: TSchema): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * @param message The error message. + * + * @returns An object schema. + */ +declare function required | undefined>(schema: TSchema, message: TMessage): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function required>(schema: TSchema, keys: TKeys): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * @param message The error message. + * + * @returns An object schema. + */ +declare function required, const TMessage extends ErrorMessage | undefined>(schema: TSchema, keys: TKeys, message: TMessage): SchemaWithRequired; + +/** + * Schema type. + */ +type Schema = NoPipe | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Required entries type. + */ +type RequiredEntries | undefined> = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? NonOptionalSchemaAsync : TEntries[TKey] : NonOptionalSchemaAsync; +}; +/** + * Schema with required type. + */ +type SchemaWithRequiredAsync | undefined, TMessage extends ErrorMessage | undefined> = TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise>, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: unknown; + }, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: InferOutput; + }, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function requiredAsync(schema: TSchema): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * @param message The error message. + * + * @returns An object schema. + */ +declare function requiredAsync | undefined>(schema: TSchema, message: TMessage): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function requiredAsync>(schema: TSchema, keys: TKeys): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * @param message The error message. + * + * @returns An object schema. + */ +declare function requiredAsync, const TMessage extends ErrorMessage | undefined>(schema: TSchema, keys: TKeys, message: TMessage): SchemaWithRequiredAsync; + +/** + * Safe parse result type. + */ +type SafeParseResult> | BaseSchemaAsync>> = { + /** + * Whether is's typed. + */ + readonly typed: true; + /** + * Whether it's successful. + */ + readonly success: true; + /** + * The output value. + */ + readonly output: InferOutput; + /** + * The issues if any. + */ + readonly issues: undefined; +} | { + readonly typed: true; + readonly success: false; + readonly output: InferOutput; + readonly issues: [InferIssue, ...InferIssue[]]; +} | { + readonly typed: false; + readonly success: false; + readonly output: unknown; + readonly issues: [InferIssue, ...InferIssue[]]; +}; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parse result. + */ +declare function safeParse>>(schema: TSchema, input: unknown, config?: Config>): SafeParseResult; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parse result. + */ +declare function safeParseAsync> | BaseSchemaAsync>>(schema: TSchema, input: unknown, config?: Config>): Promise>; + +/** + * The safe parser type. + */ +interface SafeParser>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): SafeParseResult; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function safeParser>>(schema: TSchema): SafeParser; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function safeParser>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): SafeParser; + +/** + * The safe parser async type. + */ +interface SafeParserAsync> | BaseSchemaAsync>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): Promise>; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function safeParserAsync> | BaseSchemaAsync>>(schema: TSchema): SafeParserAsync; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function safeParserAsync> | BaseSchemaAsync>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): SafeParserAsync; + +/** + * Unwraps the wrapped schema. + * + * @param schema The schema to be unwrapped. + * + * @returns The unwrapped schema. + */ +declare function unwrap>, ErrorMessage | undefined> | NonNullableSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NonNullishSchema>, ErrorMessage | undefined> | NonNullishSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NonOptionalSchema>, ErrorMessage | undefined> | NonOptionalSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NullableSchema>, unknown> | NullableSchemaAsync> | BaseSchemaAsync>, unknown> | NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>>(schema: TSchema): TSchema['wrapped']; + +/** + * Record issue type. + */ +interface RecordIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'record'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} +/** + * Is literal type. + */ +type IsLiteral = string extends TKey ? false : number extends TKey ? false : symbol extends TKey ? false : TKey extends Brand ? false : true; +/** + * Optional keys type. + */ +type OptionalKeys> = { + [TKey in keyof TObject]: IsLiteral extends true ? TKey : never; +}[keyof TObject]; +/** + * With question marks type. + * + * Hint: We mark an entry as optional if we detect that its key is a literal + * type. The reason for this is that it is not technically possible to detect + * missing literal keys without restricting the key schema to `string`, `enum` + * and `picklist`. However, if `enum` and `picklist` are used, it is better to + * use `object` with `entriesFromList` because it already covers the needed + * functionality. This decision also reduces the bundle size of `record`, + * because it only needs to check the entries of the input and not any missing + * keys. + */ +type WithQuestionMarks> = MarkOptional>; +/** + * With readonly type. + */ +type WithReadonly> | BaseSchemaAsync>, TObject extends WithQuestionMarks>> = TValue extends SchemaWithPipe<[ + BaseSchema>, + ...PipeItem>[] +]> | SchemaWithPipeAsync<[ + (BaseSchema> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] +]> ? 'readonly' extends TValue['pipe'][number]['type'] ? Readonly : TObject : TObject; +/** + * Infer record input type. + */ +type InferRecordInput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Prettify, InferInput>>>; +/** + * Infer record output type. + */ +type InferRecordOutput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Prettify, InferOutput>>>>; + +/** + * Record schema type. + */ +interface RecordSchema>, TValue extends BaseSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferRecordOutput, RecordIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'record'; + /** + * The schema reference. + */ + readonly reference: typeof record; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The record key schema. + */ + readonly key: TKey; + /** + * The record value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A record schema. + */ +declare function record>, const TValue extends BaseSchema>>(key: TKey, value: TValue): RecordSchema; +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A record schema. + */ +declare function record>, const TValue extends BaseSchema>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): RecordSchema; + +/** + * Record schema async type. + */ +interface RecordSchemaAsync> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferRecordOutput, RecordIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'record'; + /** + * The schema reference. + */ + readonly reference: typeof recordAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The record key schema. + */ + readonly key: TKey; + /** + * The record value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A record schema. + */ +declare function recordAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>>(key: TKey, value: TValue): RecordSchemaAsync; +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A record schema. + */ +declare function recordAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): RecordSchemaAsync; + +/** + * Set issue type. + */ +interface SetIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'set'; + /** + * The expected property. + */ + readonly expected: 'Set'; +} +/** + * Infer set input type. + */ +type InferSetInput> | BaseSchemaAsync>> = Set>; +/** + * Infer set output type. + */ +type InferSetOutput> | BaseSchemaAsync>> = Set>; + +/** + * Set schema type. + */ +interface SetSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferSetOutput, SetIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'set'; + /** + * The schema reference. + */ + readonly reference: typeof set; + /** + * The expected property. + */ + readonly expects: 'Set'; + /** + * The set value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a set schema. + * + * @param value The value schema. + * + * @returns A set schema. + */ +declare function set>>(value: TValue): SetSchema; +/** + * Creates a set schema. + * + * @param value The value schema. + * @param message The error message. + * + * @returns A set schema. + */ +declare function set>, const TMessage extends ErrorMessage | undefined>(value: TValue, message: TMessage): SetSchema; + +/** + * Set schema async type. + */ +interface SetSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferSetOutput, SetIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'set'; + /** + * The schema reference. + */ + readonly reference: typeof setAsync; + /** + * The expected property. + */ + readonly expects: 'Set'; + /** + * The set value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a set schema. + * + * @param value The value schema. + * + * @returns A set schema. + */ +declare function setAsync> | BaseSchemaAsync>>(value: TValue): SetSchemaAsync; +/** + * Creates a set schema. + * + * @param value The value schema. + * @param message The error message. + * + * @returns A set schema. + */ +declare function setAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(value: TValue, message: TMessage): SetSchemaAsync; + +/** + * Strict object issue type. + */ +interface StrictObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'strict_object'; + /** + * The expected property. + */ + readonly expected: 'Object' | 'never'; +} + +/** + * Strict object schema type. + */ +interface StrictObjectSchema | undefined> extends BaseSchema, InferObjectOutput, StrictObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'strict_object'; + /** + * The schema reference. + */ + readonly reference: typeof strictObject; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * + * @returns A strict object schema. + */ +declare function strictObject(entries: TEntries): StrictObjectSchema; +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A strict object schema. + */ +declare function strictObject | undefined>(entries: TEntries, message: TMessage): StrictObjectSchema; + +/** + * Strict object schema async type. + */ +interface StrictObjectSchemaAsync | undefined> extends BaseSchemaAsync, InferObjectOutput, StrictObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'strict_object'; + /** + * The schema reference. + */ + readonly reference: typeof strictObjectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * + * @returns A strict object schema. + */ +declare function strictObjectAsync(entries: TEntries): StrictObjectSchemaAsync; +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A strict object schema. + */ +declare function strictObjectAsync | undefined>(entries: TEntries, message: TMessage): StrictObjectSchemaAsync; + +/** + * Strict tuple issue type. + */ +interface StrictTupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'strict_tuple'; + /** + * The expected property. + */ + readonly expected: 'Array' | 'never'; +} + +/** + * Strict tuple schema type. + */ +interface StrictTupleSchema | undefined> extends BaseSchema, InferTupleOutput, StrictTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'strict_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof strictTuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * + * @returns A strict tuple schema. + */ +declare function strictTuple(items: TItems): StrictTupleSchema; +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A strict tuple schema. + */ +declare function strictTuple | undefined>(items: TItems, message: TMessage): StrictTupleSchema; + +/** + * Strict tuple schema async type. + */ +interface StrictTupleSchemaAsync | undefined> extends BaseSchemaAsync, InferTupleOutput, StrictTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'strict_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof strictTupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * + * @returns A strict tuple schema. + */ +declare function strictTupleAsync(items: TItems): StrictTupleSchemaAsync; +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A strict tuple schema. + */ +declare function strictTupleAsync | undefined>(items: TItems, message: TMessage): StrictTupleSchemaAsync; + +/** + * String issue type. + */ +interface StringIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'string'; + /** + * The expected property. + */ + readonly expected: 'string'; +} +/** + * String schema type. + */ +interface StringSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'string'; + /** + * The schema reference. + */ + readonly reference: typeof string; + /** + * The expected property. + */ + readonly expects: 'string'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a string schema. + * + * @returns A string schema. + */ +declare function string(): StringSchema; +/** + * Creates a string schema. + * + * @param message The error message. + * + * @returns A string schema. + */ +declare function string | undefined>(message: TMessage): StringSchema; + +/** + * Symbol issue type. + */ +interface SymbolIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'symbol'; + /** + * The expected property. + */ + readonly expected: 'symbol'; +} +/** + * Symbol schema type. + */ +interface SymbolSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'symbol'; + /** + * The schema reference. + */ + readonly reference: typeof symbol; + /** + * The expected property. + */ + readonly expects: 'symbol'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a symbol schema. + * + * @returns A symbol schema. + */ +declare function symbol(): SymbolSchema; +/** + * Creates a symbol schema. + * + * @param message The error message. + * + * @returns A symbol schema. + */ +declare function symbol | undefined>(message: TMessage): SymbolSchema; + +/** + * Tuple issue type. + */ +interface TupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'tuple'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Tuple schema type. + */ +interface TupleSchema | undefined> extends BaseSchema, InferTupleOutput, TupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'tuple'; + /** + * The schema reference. + */ + readonly reference: typeof tuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTuple`. To + * return an issue for unknown items, use `strictTuple`. To include and + * validate unknown items, use `tupleWithRest`. + * + * @param items The items schema. + * + * @returns A tuple schema. + */ +declare function tuple(items: TItems): TupleSchema; +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTuple`. To + * return an issue for unknown items, use `strictTuple`. To include and + * validate unknown items, use `tupleWithRest`. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A tuple schema. + */ +declare function tuple | undefined>(items: TItems, message: TMessage): TupleSchema; + +/** + * Tuple schema async type. + */ +interface TupleSchemaAsync | undefined> extends BaseSchemaAsync, InferTupleOutput, TupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'tuple'; + /** + * The schema reference. + */ + readonly reference: typeof tupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTupleAsync`. To + * return an issue for unknown items, use `strictTupleAsync`. To include and + * validate unknown items, use `tupleWithRestAsync`. + * + * @param items The items schema. + * + * @returns A tuple schema. + */ +declare function tupleAsync(items: TItems): TupleSchemaAsync; +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTupleAsync`. To + * return an issue for unknown items, use `strictTupleAsync`. To include and + * validate unknown items, use `tupleWithRestAsync`. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A tuple schema. + */ +declare function tupleAsync | undefined>(items: TItems, message: TMessage): TupleSchemaAsync; + +/** + * Tuple with rest issue type. + */ +interface TupleWithRestIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'tuple_with_rest'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Tuple with rest schema type. + */ +interface TupleWithRestSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema<[ + ...InferTupleInput, + ...InferInput[] +], [ + ...InferTupleOutput, + ...InferOutput[] +], TupleWithRestIssue | InferTupleIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'tuple_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof tupleWithRest; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRest>>(items: TItems, rest: TRest): TupleWithRestSchema; +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRest>, const TMessage extends ErrorMessage | undefined>(items: TItems, rest: TRest, message: TMessage): TupleWithRestSchema; + +/** + * Tuple with rest schema async type. + */ +interface TupleWithRestSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync<[ + ...InferTupleInput, + ...InferInput[] +], [ + ...InferTupleOutput, + ...InferOutput[] +], TupleWithRestIssue | InferTupleIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'tuple_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof tupleWithRestAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRestAsync> | BaseSchemaAsync>>(items: TItems, rest: TRest): TupleWithRestSchemaAsync; +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRestAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(items: TItems, rest: TRest, message: TMessage): TupleWithRestSchemaAsync; + +/** + * Undefined issue type. + */ +interface UndefinedIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'undefined'; + /** + * The expected property. + */ + readonly expected: 'undefined'; +} +/** + * Undefined schema type. + */ +interface UndefinedSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'undefined'; + /** + * The schema reference. + */ + readonly reference: typeof undefined_; + /** + * The expected property. + */ + readonly expects: 'undefined'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an undefined schema. + * + * @returns An undefined schema. + */ +declare function undefined_(): UndefinedSchema; +/** + * Creates an undefined schema. + * + * @param message The error message. + * + * @returns An undefined schema. + */ +declare function undefined_ | undefined>(message: TMessage): UndefinedSchema; + +/** + * Unknown schema type. + */ +interface UnknownSchema extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'unknown'; + /** + * The schema reference. + */ + readonly reference: typeof unknown; + /** + * The expected property. + */ + readonly expects: 'unknown'; +} +/** + * Creates a unknown schema. + * + * @returns A unknown schema. + */ +declare function unknown(): UnknownSchema; + +/** + * Variant schema type. + */ +interface VariantSchema, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferOutput, VariantIssue | InferVariantIssue> { + /** + * The schema type. + */ + readonly type: 'variant'; + /** + * The schema reference. + */ + readonly reference: typeof variant; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The discriminator key. + */ + readonly key: TKey; + /** + * The variant options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * + * @returns A variant schema. + */ +declare function variant>(key: TKey, options: TOptions): VariantSchema; +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * @param message The error message. + * + * @returns An variant schema. + */ +declare function variant, const TMessage extends ErrorMessage | undefined>(key: TKey, options: TOptions, message: TMessage): VariantSchema; + +/** + * Variant schema async type. + */ +interface VariantSchemaAsync, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferOutput, VariantIssue | InferVariantIssue> { + /** + * The schema type. + */ + readonly type: 'variant'; + /** + * The schema reference. + */ + readonly reference: typeof variantAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The discriminator key. + */ + readonly key: TKey; + /** + * The variant options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * + * @returns A variant schema. + */ +declare function variantAsync>(key: TKey, options: TOptions): VariantSchemaAsync; +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * @param message The error message. + * + * @returns An variant schema. + */ +declare function variantAsync, const TMessage extends ErrorMessage | undefined>(key: TKey, options: TOptions, message: TMessage): VariantSchemaAsync; + +/** + * Variant issue type. + */ +interface VariantIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'variant'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Variant option schema type. + */ +interface VariantOptionSchema extends BaseSchema> { + readonly type: 'variant'; + readonly reference: typeof variant; + readonly key: string; + readonly options: VariantOptions; + readonly message: ErrorMessage | undefined; +} +/** + * Variant option schema async type. + */ +interface VariantOptionSchemaAsync extends BaseSchemaAsync> { + readonly type: 'variant'; + readonly reference: typeof variantAsync; + readonly key: string; + readonly options: VariantOptionsAsync; + readonly message: ErrorMessage | undefined; +} +/** + * Variant option type. + */ +type VariantOption = LooseObjectSchema>>, ErrorMessage | undefined> | ObjectSchema>>, ErrorMessage | undefined> | ObjectWithRestSchema>>, BaseSchema>, ErrorMessage | undefined> | StrictObjectSchema>>, ErrorMessage | undefined> | VariantOptionSchema; +/** + * Variant option async type. + */ +type VariantOptionAsync = LooseObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | ObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>>, BaseSchema> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | VariantOptionSchemaAsync; +/** + * Variant options type. + */ +type VariantOptions = MaybeReadonly[]>; +/** + * Variant options async type. + */ +type VariantOptionsAsync = MaybeReadonly<(VariantOption | VariantOptionAsync)[]>; +/** + * Infer variant issue type. + */ +type InferVariantIssue | VariantOptionsAsync> = Exclude, { + type: 'loose_object' | 'object' | 'object_with_rest'; +}>; + +/** + * Void issue type. + */ +interface VoidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'void'; + /** + * The expected property. + */ + readonly expected: 'void'; +} +/** + * Void schema type. + */ +interface VoidSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'void'; + /** + * The schema reference. + */ + readonly reference: typeof void_; + /** + * The expected property. + */ + readonly expects: 'void'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a void schema. + * + * @returns A void schema. + */ +declare function void_(): VoidSchema; +/** + * Creates a void schema. + * + * @param message The error message. + * + * @returns A void schema. + */ +declare function void_ | undefined>(message: TMessage): VoidSchema; + +/** + * Base metadata type. + */ +interface BaseMetadata { + /** + * The object kind. + */ + readonly kind: 'metadata'; + /** + * The metadata type. + */ + readonly type: string; + /** + * The metadata reference. + */ + readonly reference: (...args: any[]) => BaseMetadata; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TInput; + readonly issue: never; + }; +} +/** + * Generic metadata type. + */ +interface GenericMetadata extends BaseMetadata { +} + +/** + * Typed dataset type. + */ +interface TypedDataset> { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue; + /** + * The dataset issues. + */ + issues?: [TIssue, ...TIssue[]]; +} +/** + * Untyped dataset type. + */ +interface UntypedDataset> { + /** + * Whether is's typed. + */ + typed: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues?: [TIssue, ...TIssue[]]; +} +/** + * Dataset type. + */ +type Dataset> = TypedDataset | UntypedDataset; + +/** + * Base schema type. + */ +interface BaseSchema> { + /** + * The object kind. + */ + readonly kind: 'schema'; + /** + * The schema type. + */ + readonly type: string; + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema>; + /** + * The expected property. + */ + readonly expects: string; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config) => Dataset; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base schema async type. + */ +interface BaseSchemaAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema> | BaseSchemaAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config) => Promise>; +} +/** + * Generic schema type. + */ +interface GenericSchema = BaseIssue> extends BaseSchema { +} +/** + * Generic schema async type. + */ +interface GenericSchemaAsync = BaseIssue> extends BaseSchemaAsync { +} + +/** + * Base transformation type. + */ +interface BaseTransformation> { + /** + * The object kind. + */ + readonly kind: 'transformation'; + /** + * The transformation type. + */ + readonly type: string; + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Transforms known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: TypedDataset, config: Config) => Dataset; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base transformation async type. + */ +interface BaseTransformationAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation | BaseTransformationAsync; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Transforms known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: TypedDataset, config: Config) => Promise>; +} +/** + * Generic transformation type. + */ +interface GenericTransformation = BaseIssue> extends BaseTransformation { +} +/** + * Generic transformation async type. + */ +interface GenericTransformationAsync = BaseIssue> extends BaseTransformationAsync { +} + +/** + * Base validation type. + */ +interface BaseValidation> { + /** + * The object kind. + */ + readonly kind: 'validation'; + /** + * The validation type. + */ + readonly type: string; + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation; + /** + * The expected property. + */ + readonly expects: string | null; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Validates known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset>, config: Config) => Dataset | TIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base validation async type. + */ +interface BaseValidationAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation | BaseValidationAsync; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Validates known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset>, config: Config) => Promise | TIssue>>; +} +/** + * Generic validation type. + */ +interface GenericValidation = BaseIssue> extends BaseValidation { +} +/** + * Generic validation async type. + */ +interface GenericValidationAsync = BaseIssue> extends BaseValidationAsync { +} + +/** + * Infer input type. + */ +type InferInput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['input']; +/** + * Infer output type. + */ +type InferOutput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['output']; +/** + * Infer issue type. + */ +type InferIssue> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['issue']; + +/** + * Extracts `null` from a type. + */ +type NonNullable$1 = TValue extends null ? never : TValue; +/** + * Extracts `null` and `undefined` from a type. + */ +type NonNullish = TValue extends null | undefined ? never : TValue; +/** + * Extracts `undefined` from a type. + */ +type NonOptional = TValue extends undefined ? never : TValue; +/** + * Constructs a type that is maybe readonly. + */ +type MaybeReadonly = TValue | Readonly; +/** + * Constructs a type that is maybe a promise. + */ +type MaybePromise = TValue | Promise; +/** + * Prettifies a type for better readability. + * + * Hint: This type has no effect and is only used so that TypeScript displays + * the final type in the preview instead of the utility types used. + */ +type Prettify = { + [TKey in keyof TObject]: TObject[TKey]; +} & {}; +/** + * Marks specific keys as optional. + */ +type MarkOptional = Omit & Partial>; +/** + * Extracts first tuple item. + */ +type FirstTupleItem = TTuple[0]; +/** + * Extracts last tuple item. + */ +type LastTupleItem = TTuple[TTuple extends [unknown, ...infer TRest] ? TRest['length'] : never]; +/** + * Converts union to intersection type. + */ +type UnionToIntersect = (TUnion extends any ? (arg: TUnion) => void : never) extends (arg: infer Intersect) => void ? Intersect : never; +/** + * Converts union to tuple type. + */ +type UnionToTuple = UnionToIntersect TUnion> extends () => infer TLast ? [...UnionToTuple>, TLast] : []; +/** + * Extracts tuples with path keys. + */ +type PathKeys = MaybeReadonly] : { + [TKey in keyof TValue]: TKey extends `${infer TIndex extends number}` ? [TIndex] | [TIndex, ...PathKeys] : never; +}[keyof TValue & number] : TValue extends Record ? { + [TKey in keyof TValue]: [TKey] | [TKey, ...PathKeys]; +}[keyof TValue] : never>; +/** + * Deeply picks specific keys. + * + * Hint: If this type is ever exported and accessible from the outside, it must + * be wrapped in `UnionToIntersect` to avoid invalid results. + */ +type DeepPick> = TPathKeys extends readonly [infer TPathKey, ...infer TPathRest] ? TValue extends readonly unknown[] ? number extends TValue['length'] ? TPathRest extends PathKeys ? DeepPick[] : TValue : TPathKey extends string | number ? { + [TKey in keyof TValue]: TKey extends `${TPathKey}` ? TPathRest extends PathKeys ? DeepPick : TValue[TKey] : unknown; +} : never : { + [TKey in keyof TValue as TKey extends TPathKey ? TKey : never]: TPathRest extends PathKeys ? DeepPick : TValue[TKey]; +} : never; +/** + * Deeply merges two types. + */ +type DeepMerge = TValue1 extends readonly unknown[] ? TValue2 extends readonly unknown[] ? number extends TValue1['length'] | TValue2['length'] ? DeepMerge[] : { + [TKey in keyof TValue1]: TKey extends keyof TValue2 ? unknown extends TValue1[TKey] ? TValue2[TKey] : TValue1[TKey] : never; +} : never : TValue1 extends Record ? TValue2 extends Record ? { + [TKey in keyof (TValue1 & TValue2)]: TKey extends keyof TValue1 ? TKey extends keyof TValue2 ? DeepMerge : TValue1[TKey] : TKey extends keyof TValue2 ? TValue2[TKey] : never; +} : never : TValue1 & TValue2; +/** + * Deeply picks N specific keys. + */ +type DeepPickN[]> = TPathList extends readonly [ + infer TPathKeys extends PathKeys, + ...infer TRest extends PathKeys[] +] ? TRest extends readonly [unknown, ...(readonly unknown[])] ? DeepMerge, DeepPickN> : DeepPick : TInput; + +/** + * Error message type. + */ +type ErrorMessage> = ((issue: TIssue) => string) | string; +/** + * Default type. + */ +type Default>, TInput extends null | undefined> = MaybeReadonly | TInput> | ((dataset?: Dataset, config?: Config>) => MaybeReadonly | TInput>); +/** + * Default async type. + */ +type DefaultAsync> | BaseSchemaAsync>, TInput extends null | undefined> = MaybeReadonly | TInput> | ((dataset?: Dataset, config?: Config>) => MaybePromise | TInput>>); +/** + * Default value type. + */ +type DefaultValue>, null | undefined> | DefaultAsync> | BaseSchemaAsync>, null | undefined>> = TDefault extends DefaultAsync> | BaseSchemaAsync>, infer TInput> ? TDefault extends (dataset?: Dataset, config?: Config>) => MaybePromise | TInput> ? Awaited> : TDefault : never; + +/** + * Pipe action type. + */ +type PipeAction> = BaseValidation | BaseTransformation | BaseMetadata; +/** + * Pipe action async type. + */ +type PipeActionAsync> = BaseValidationAsync | BaseTransformationAsync; +/** + * Pipe item type. + */ +type PipeItem> = BaseSchema | PipeAction; +/** + * Pipe item async type. + */ +type PipeItemAsync> = BaseSchemaAsync | PipeActionAsync; +/** + * No pipe type. + */ +type NoPipe> | BaseSchemaAsync>> = TSchema & { + pipe?: never; +}; + +/** + * Object entries type. + */ +interface ObjectEntries { + [key: string]: BaseSchema>; +} +/** + * Object entries async type. + */ +interface ObjectEntriesAsync { + [key: string]: BaseSchema> | BaseSchemaAsync>; +} +/** + * Object keys type. + */ +type ObjectKeys | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>> = MaybeReadonly<[keyof TSchema['entries'], ...(keyof TSchema['entries'])[]]>; +/** + * Infer entries input type. + */ +type InferEntriesInput = { + -readonly [TKey in keyof TEntries]: InferInput; +}; +/** + * Infer entries output type. + */ +type InferEntriesOutput = { + -readonly [TKey in keyof TEntries]: InferOutput; +}; +/** + * Question mark schema type. + * + * TODO: Document that for simplicity and bundle size, we currently do not + * distinguish between `undefined` and missing keys when using `optional` and + * `nullish`. + */ +type QuestionMarkSchema = NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>; +/** + * Optional input keys type. + */ +type OptionalInputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends QuestionMarkSchema ? TKey : never; +}[keyof TEntries]; +/** + * Optional output keys type. + */ +type OptionalOutputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends QuestionMarkSchema ? [TEntries[TKey]['default']] extends [never] ? TKey : never : never; +}[keyof TEntries]; +/** + * Input with question marks type. + */ +type InputWithQuestionMarks | InferEntriesOutput> = MarkOptional>; +/** + * Output with question marks type. + */ +type OutputWithQuestionMarks | InferEntriesOutput> = MarkOptional>; +/** + * Readonly output keys type. + */ +type ReadonlyOutputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends SchemaWithPipe<[ + BaseSchema>, + ...PipeItem>[] + ]> | SchemaWithPipeAsync<[ + (BaseSchema> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] + ]> ? 'readonly' extends TEntries[TKey]['pipe'][number]['type'] ? TKey : never : never; +}[keyof TEntries]; +/** + * Output with readonly type. + */ +type OutputWithReadonly>> = Readonly & Pick>>; +/** + * Infer object input type. + */ +type InferObjectInput = Prettify>>; +/** + * Infer object output type. + */ +type InferObjectOutput = Prettify>>>; +/** + * Infer object issue type. + */ +type InferObjectIssue = InferIssue; + +/** + * Tuple items type. + */ +type TupleItems = MaybeReadonly>[]>; +/** + * Tuple items async type. + */ +type TupleItemsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Infer tuple input type. + */ +type InferTupleInput = { + -readonly [TKey in keyof TItems]: InferInput; +}; +/** + * Infer tuple output type. + */ +type InferTupleOutput = { + -readonly [TKey in keyof TItems]: InferOutput; +}; +/** + * Infer tuple issue type. + */ +type InferTupleIssue = InferIssue; + +/** + * Array path item type. + */ +interface ArrayPathItem { + /** + * The path item type. + */ + readonly type: 'array'; + /** + * The path item origin. + */ + readonly origin: 'value'; + /** + * The path item input. + */ + readonly input: MaybeReadonly; + /** + * The path item key. + */ + readonly key: number; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Map path item type. + */ +interface MapPathItem { + /** + * The path item type. + */ + readonly type: 'map'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: Map; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Object path item type. + */ +interface ObjectPathItem { + /** + * The path item type. + */ + readonly type: 'object'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: Record; + /** + * The path item key. + */ + readonly key: string; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Set path item type. + */ +interface SetPathItem { + /** + * The path item type. + */ + readonly type: 'set'; + /** + * The path item origin. + */ + readonly origin: 'value'; + /** + * The path item input. + */ + readonly input: Set; + /** + * The path item key. + */ + readonly key: null; + /** + * The path item key. + */ + readonly value: unknown; +} +/** + * Unknown path item type. + */ +interface UnknownPathItem { + /** + * The path item type. + */ + readonly type: 'unknown'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: unknown; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Issue path item type. + * + * TODO: Document that the input of the path may be different from the input of + * the issue. + */ +type IssuePathItem = ArrayPathItem | MapPathItem | ObjectPathItem | SetPathItem | UnknownPathItem; +/** + * Base issue type. + */ +interface BaseIssue extends Config> { + /** + * The issue kind. + */ + readonly kind: 'schema' | 'validation' | 'transformation'; + /** + * The issue type. + */ + readonly type: string; + /** + * The raw input data. + */ + readonly input: TInput; + /** + * The expected property. + */ + readonly expected: string | null; + /** + * The received property. + */ + readonly received: string; + /** + * The error message. + */ + readonly message: string; + /** + * The input requirement. + */ + readonly requirement?: unknown; + /** + * The issue path. + * + * TODO: Investigate if it is possible to make the path type safe based on the + * input. + */ + readonly path?: [IssuePathItem, ...IssuePathItem[]]; + /** + * The sub issues. + */ + readonly issues?: [BaseIssue, ...BaseIssue[]]; +} +/** + * Generic issue type. + */ +interface GenericIssue extends BaseIssue { +} +/** + * Dot path type. + */ +type DotPath> | BaseSchemaAsync>> = TKey extends string | number ? `${TKey}` | `${TKey}.${IssueDotPath}` : never; +/** + * Object path type. + */ +type ObjectPath = { + [TKey in keyof TEntries]: DotPath; +}[keyof TEntries]; +/** + * Tuple keys type. + */ +type TupleKeys = Exclude; +/** + * Tuple path type. + */ +type TuplePath = { + [TKey in TupleKeys]: TItems[TKey] extends BaseSchema> | BaseSchemaAsync> ? DotPath : never; +}[TupleKeys]; +/** + * Issue dot path type. + */ +type IssueDotPath> | BaseSchemaAsync>> = TSchema extends ArraySchema | undefined> | ArraySchemaAsync | undefined> ? DotPath : TSchema extends IntersectSchema | undefined> | IntersectSchemaAsync | undefined> | UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? IssueDotPath : TSchema extends MapSchema | undefined> | MapSchemaAsync | undefined> | RecordSchema | undefined> | RecordSchemaAsync | undefined> ? DotPath, TValue> : TSchema extends LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> ? ObjectPath : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> ? string : TSchema extends SetSchema | undefined> | SetSchemaAsync | undefined> ? DotPath : TSchema extends LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> ? TuplePath : TSchema extends TupleWithRestSchema | undefined> | TupleWithRestSchemaAsync | undefined> ? TuplePath | DotPath : TSchema extends LazySchema | LazySchemaAsync | NonNullableSchema | undefined> | NonNullableSchemaAsync | undefined> | NonNullishSchema | undefined> | NonNullishSchemaAsync | undefined> | NonOptionalSchema | undefined> | NonOptionalSchemaAsync | undefined> | NullableSchema>, null>> | NullableSchemaAsync> | BaseSchemaAsync>, null>> | NullishSchema>, null | undefined>> | NullishSchemaAsync> | BaseSchemaAsync>, null | undefined>> | OptionalSchema>, undefined>> | OptionalSchemaAsync> | BaseSchemaAsync>, undefined>> ? IssueDotPath : never; + +/** + * Config type. + */ +interface Config> { + /** + * The selected language. + */ + readonly lang?: string; + /** + * The error message. + */ + readonly message?: ErrorMessage; + /** + * Whether it was abort early. + */ + readonly abortEarly?: boolean; + /** + * Whether the pipe was abort early. + */ + readonly abortPipeEarly?: boolean; +} + +/** + * Await action async type. + */ +interface AwaitActionAsync> extends BaseTransformationAsync, never> { + /** + * The action type. + */ + readonly type: 'await'; + /** + * The action reference. + */ + readonly reference: typeof awaitAsync; +} +/** + * Creates an await transformation action. + * + * @returns An await action. + */ +declare function awaitAsync>(): AwaitActionAsync; + +/** + * Base64 issue type. + */ +interface Base64Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'base64'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The Base64 regex. + */ + readonly requirement: RegExp; +} +/** + * Base64 action type. + */ +interface Base64Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'base64'; + /** + * The action reference. + */ + readonly reference: typeof base64; + /** + * The expected property. + */ + readonly expects: null; + /** + * The Base64 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [Base64](https://en.wikipedia.org/wiki/Base64) validation action. + * + * @returns A Base64 action. + */ +declare function base64(): Base64Action; +/** + * Creates a [Base64](https://en.wikipedia.org/wiki/Base64) validation action. + * + * @param message The error message. + * + * @returns A Base64 action. + */ +declare function base64> | undefined>(message: TMessage): Base64Action; + +/** + * BIC issue type. + */ +interface BicIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'bic'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The BIC regex. + */ + readonly requirement: RegExp; +} +/** + * BIC action type. + */ +interface BicAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'bic'; + /** + * The action reference. + */ + readonly reference: typeof bic; + /** + * The expected property. + */ + readonly expects: null; + /** + * The BIC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [BIC](https://en.wikipedia.org/wiki/ISO_9362) validation action. + * + * @returns A BIC action. + */ +declare function bic(): BicAction; +/** + * Creates a [BIC](https://en.wikipedia.org/wiki/ISO_9362) validation action. + * + * @param message The error message. + * + * @returns A BIC action. + */ +declare function bic> | undefined>(message: TMessage): BicAction; + +/** + * Brand symbol. + */ +declare const BrandSymbol: unique symbol; +/** + * Brand name type. + */ +type BrandName = string | number | symbol; +/** + * Brand type. + */ +interface Brand { + [BrandSymbol]: { + [TValue in TName]: TValue; + }; +} +/** + * Brand action type. + */ +interface BrandAction extends BaseTransformation, never> { + /** + * The action type. + */ + readonly type: 'brand'; + /** + * The action reference. + */ + readonly reference: typeof brand; + /** + * The brand name. + */ + readonly name: TName; +} +/** + * Creates a brand transformation action. + * + * @param name The brand name. + * + * @returns A brand action. + */ +declare function brand(name: TName): BrandAction; + +/** + * Bytes issue type. + */ +interface BytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'bytes'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required bytes. + */ + readonly requirement: TRequirement; +} +/** + * Bytes action type. + */ +interface BytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'bytes'; + /** + * The action reference. + */ + readonly reference: typeof bytes; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The required bytes. + * + * @returns A bytes action. + */ +declare function bytes(requirement: TRequirement): BytesAction; +/** + * Creates a [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The required bytes. + * @param message The error message. + * + * @returns A bytes action. + */ +declare function bytes> | undefined>(requirement: TRequirement, message: TMessage): BytesAction; + +/** + * Check issue type. + */ +interface CheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'check'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; +} + +/** + * Check action type. + */ +interface CheckAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'check'; + /** + * The action reference. + */ + readonly reference: typeof check; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * + * @returns A check action. + */ +declare function check(requirement: (input: TInput) => boolean): CheckAction; +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A check action. + */ +declare function check> | undefined>(requirement: (input: TInput) => boolean, message: TMessage): CheckAction; + +/** + * Check action async type. + */ +interface CheckActionAsync> | undefined> extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'check'; + /** + * The action reference. + */ + readonly reference: typeof checkAsync; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * + * @returns A check action. + */ +declare function checkAsync(requirement: (input: TInput) => MaybePromise): CheckActionAsync; +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A check action. + */ +declare function checkAsync> | undefined>(requirement: (input: TInput) => MaybePromise, message: TMessage): CheckActionAsync; + +/** + * Array input type. + */ +type ArrayInput = MaybeReadonly; +/** + * Array requirement type. + */ +type ArrayRequirement = (item: TInput[number], index: number, array: TInput) => boolean; +/** + * Content input type. + */ +type ContentInput = string | MaybeReadonly; +/** + * Content requirement type. + */ +type ContentRequirement = TInput extends readonly unknown[] ? TInput[number] : TInput; +/** + * Length input type. + */ +type LengthInput = string | ArrayLike; +/** + * Size input type. + */ +type SizeInput = Blob | Map | Set; +/** + * Value input type. + */ +type ValueInput = string | number | bigint | boolean | Date; + +/** + * Check items issue type. + */ +interface CheckItemsIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'check_items'; + /** + * The expected input. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Check items action type. + */ +interface CheckItemsAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'check_items'; + /** + * The action reference. + */ + readonly reference: typeof checkItems; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an check items validation action. + * + * @param requirement The validation function. + * + * @returns An check items action. + */ +declare function checkItems(requirement: ArrayRequirement): CheckItemsAction; +/** + * Creates an check items validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns An check items action. + */ +declare function checkItems> | undefined>(requirement: ArrayRequirement, message: TMessage): CheckItemsAction; + +/** + * Credit card issue type. + */ +interface CreditCardIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'credit_card'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * Credit card action type. + */ +interface CreditCardAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'credit_card'; + /** + * The action reference. + */ + readonly reference: typeof creditCard; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [credit card](https://en.wikipedia.org/wiki/Payment_card_number) validation action. + * + * @returns A Credit card action. + */ +declare function creditCard(): CreditCardAction; +/** + * Creates a [credit card](https://en.wikipedia.org/wiki/Payment_card_number) validation action. + * + * @param message The error message. + * + * @returns A credit card action. + */ +declare function creditCard> | undefined>(message: TMessage): CreditCardAction; + +/** + * Cuid2 issue type. + */ +interface Cuid2Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'cuid2'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The Cuid2 regex. + */ + readonly requirement: RegExp; +} +/** + * Cuid2 action type. + */ +interface Cuid2Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'cuid2'; + /** + * The action reference. + */ + readonly reference: typeof cuid2; + /** + * The expected property. + */ + readonly expects: null; + /** + * The Cuid2 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [Cuid2](https://github.com/paralleldrive/cuid2) validation action. + * + * @returns A Cuid2 action. + */ +declare function cuid2(): Cuid2Action; +/** + * Creates a [Cuid2](https://github.com/paralleldrive/cuid2) validation action. + * + * @param message The error message. + * + * @returns A Cuid2 action. + */ +declare function cuid2> | undefined>(message: TMessage): Cuid2Action; + +/** + * Decimal issue type. + */ +interface DecimalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'decimal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The decimal regex. + */ + readonly requirement: RegExp; +} +/** + * Decimal action type. + */ +interface DecimalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'decimal'; + /** + * The action reference. + */ + readonly reference: typeof decimal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The decimal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [decimal](https://en.wikipedia.org/wiki/Decimal) validation action. + * + * @returns An decimal action. + */ +declare function decimal(): DecimalAction; +/** + * Creates a [decimal](https://en.wikipedia.org/wiki/Decimal) validation action. + * + * @param message The error message. + * + * @returns An decimal action. + */ +declare function decimal> | undefined>(message: TMessage): DecimalAction; + +/** + * Description action type. + */ +interface DescriptionAction extends BaseMetadata { + /** + * The action type. + */ + readonly type: 'description'; + /** + * The action reference. + */ + readonly reference: typeof description; + /** + * The description text. + */ + readonly description: TDescription; +} +/** + * Creates a description metadata action. + * + * @param description_ The description text. + * + * @returns A description action. + */ +declare function description(description_: TDescription): DescriptionAction; + +/** + * Email issue type. + */ +interface EmailIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'email'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The email regex. + */ + readonly requirement: RegExp; +} +/** + * Email action type. + */ +interface EmailAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'email'; + /** + * The action reference. + */ + readonly reference: typeof email; + /** + * The expected property. + */ + readonly expects: null; + /** + * The email regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [email](https://en.wikipedia.org/wiki/Email_address) validation + * action. + * + * Hint: This validation action intentionally only validates common email + * addresses. If you are interested in an action that covers the entire + * specification, please see issue [#204](https://github.com/fabian-hiller/valibot/issues/204). + * + * @returns An email action. + */ +declare function email(): EmailAction; +/** + * Creates an [email](https://en.wikipedia.org/wiki/Email_address) validation + * action. + * + * Hint: This validation action intentionally only validates common email + * addresses. If you are interested in an action that covers the entire + * specification, please see issue [#204](https://github.com/fabian-hiller/valibot/issues/204). + * + * @param message The error message. + * + * @returns An email action. + */ +declare function email> | undefined>(message: TMessage): EmailAction; + +/** + * Emoji issue type. + */ +interface EmojiIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'emoji'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The emoji regex. + */ + readonly requirement: RegExp; +} +/** + * Emoji action type. + */ +interface EmojiAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'emoji'; + /** + * The action reference. + */ + readonly reference: typeof emoji; + /** + * The expected property. + */ + readonly expects: null; + /** + * The emoji regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [emoji](https://en.wikipedia.org/wiki/Emoji) validation action. + * + * @returns An emoji action. + */ +declare function emoji(): EmojiAction; +/** + * Creates an [emoji](https://en.wikipedia.org/wiki/Emoji) validation action. + * + * @param message The error message. + * + * @returns An emoji action. + */ +declare function emoji> | undefined>(message: TMessage): EmojiAction; + +/** + * Empty issue type. + */ +interface EmptyIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'empty'; + /** + * The expected input. + */ + readonly expected: '0'; + /** + * The received input. + */ + readonly received: `${number}`; +} +/** + * Empty action type. + */ +interface EmptyAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'empty'; + /** + * The action reference. + */ + readonly reference: typeof empty; + /** + * The expected property. + */ + readonly expects: '0'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an empty validation action. + * + * @returns An empty action. + */ +declare function empty(): EmptyAction; +/** + * Creates an empty validation action. + * + * @param message The error message. + * + * @returns An empty action. + */ +declare function empty> | undefined>(message: TMessage): EmptyAction; + +/** + * Ends with issue type. + */ +interface EndsWithIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ends_with'; + /** + * The expected property. + */ + readonly expected: `"${TRequirement}"`; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The end string. + */ + readonly requirement: TRequirement; +} +/** + * Ends with action type. + */ +interface EndsWithAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ends_with'; + /** + * The action reference. + */ + readonly reference: typeof endsWith; + /** + * The expected property. + */ + readonly expects: `"${TRequirement}"`; + /** + * The end string. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an ends with validation action. + * + * @param requirement The end string. + * + * @returns An ends with action. + */ +declare function endsWith(requirement: TRequirement): EndsWithAction; +/** + * Creates an ends with validation action. + * + * @param requirement The end string. + * @param message The error message. + * + * @returns An ends with action. + */ +declare function endsWith> | undefined>(requirement: TRequirement, message: TMessage): EndsWithAction; + +/** + * Every item issue type. + */ +interface EveryItemIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'every_item'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Every item action type. + */ +interface EveryItemAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'every_item'; + /** + * The action reference. + */ + readonly reference: typeof everyItem; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an every item validation action. + * + * @param requirement The validation function. + * + * @returns An every item action. + */ +declare function everyItem(requirement: ArrayRequirement): EveryItemAction; +/** + * Creates an every item validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns An every item action. + */ +declare function everyItem> | undefined>(requirement: ArrayRequirement, message: TMessage): EveryItemAction; + +/** + * Excludes issue type. + */ +interface ExcludesIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'excludes'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The content to be excluded. + */ + readonly requirement: TRequirement; +} +/** + * Excludes action type. + */ +interface ExcludesAction, TMessage extends ErrorMessage> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'excludes'; + /** + * The action reference. + */ + readonly reference: typeof excludes; + /** + * The expected property. + */ + readonly expects: string; + /** + * The content to be excluded. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an excludes validation action. + * + * @param requirement The content to be excluded. + * + * @returns An excludes action. + */ +declare function excludes>(requirement: TRequirement): ExcludesAction; +/** + * Creates an excludes validation action. + * + * @param requirement The content to be excluded. + * @param message The error message. + * + * @returns An excludes action. + */ +declare function excludes, const TMessage extends ErrorMessage> | undefined>(requirement: TRequirement, message: TMessage): ExcludesAction; + +/** + * Filter items action type. + */ +interface FilterItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'filter_items'; + /** + * The action reference. + */ + readonly reference: typeof filterItems; + /** + * The filter items operation. + */ + readonly operation: ArrayRequirement; +} +/** + * Creates a filter items transformation action. + * + * @param operation The filter items operation. + * + * @returns A filter items action. + */ +declare function filterItems(operation: ArrayRequirement): FilterItemsAction; + +/** + * Find item action type. + */ +interface FindItemAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'find_item'; + /** + * The action reference. + */ + readonly reference: typeof findItem; + /** + * The find item operation. + */ + readonly operation: ArrayRequirement; +} +/** + * Creates a find item transformation action. + * + * @param operation The find item operation. + * + * @returns A find item action. + */ +declare function findItem(operation: ArrayRequirement): FindItemAction; + +/** + * Finite issue type. + */ +interface FiniteIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'finite'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Finite action type. + */ +interface FiniteAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'finite'; + /** + * The action reference. + */ + readonly reference: typeof finite; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [finite](https://en.wikipedia.org/wiki/Finite) validation action. + * + * @returns A finite action. + */ +declare function finite(): FiniteAction; +/** + * Creates a [finite](https://en.wikipedia.org/wiki/Finite) validation action. + * + * @param message The error message. + * + * @returns A finite action. + */ +declare function finite> | undefined>(message: TMessage): FiniteAction; + +/** + * Hash lengths object. + */ +declare const HASH_LENGTHS: { + readonly md4: 32; + readonly md5: 32; + readonly sha1: 40; + readonly sha256: 64; + readonly sha384: 96; + readonly sha512: 128; + readonly ripemd128: 32; + readonly ripemd160: 40; + readonly tiger128: 32; + readonly tiger160: 40; + readonly tiger192: 48; + readonly crc32: 8; + readonly crc32b: 8; + readonly adler32: 8; +}; +/** + * Hash type type. + */ +type HashType = keyof typeof HASH_LENGTHS; +/** + * Hash issue type. + */ +interface HashIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hash'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hash regex. + */ + readonly requirement: RegExp; +} +/** + * Hash action type. + */ +interface HashAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hash'; + /** + * The action reference. + */ + readonly reference: typeof hash; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hash regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hash](https://en.wikipedia.org/wiki/Hash_function) validation action. + * + * @param types The hash types. + * + * @returns A hash action. + */ +declare function hash(types: [HashType, ...HashType[]]): HashAction; +/** + * Creates a [hash](https://en.wikipedia.org/wiki/Hash_function) validation action. + * + * @param types The hash types. + * @param message The error message. + * + * @returns A hash action. + */ +declare function hash> | undefined>(types: [HashType, ...HashType[]], message: TMessage): HashAction; + +/** + * Hexadecimal issue type. + */ +interface HexadecimalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hexadecimal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hexadecimal regex. + */ + readonly requirement: RegExp; +} +/** + * Hexadecimal action type. + */ +interface HexadecimalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hexadecimal'; + /** + * The action reference. + */ + readonly reference: typeof hexadecimal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hexadecimal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) validation action. + * + * @returns A hexadecimal action. + */ +declare function hexadecimal(): HexadecimalAction; +/** + * Creates a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) validation action. + * + * @param message The error message. + * + * @returns A hexadecimal action. + */ +declare function hexadecimal> | undefined>(message: TMessage): HexadecimalAction; + +/** + * Hex color issue type. + */ +interface HexColorIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hex_color'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hex color regex. + */ + readonly requirement: RegExp; +} +/** + * Hex color action type. + */ +interface HexColorAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hex_color'; + /** + * The action reference. + */ + readonly reference: typeof hexColor; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hex color regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) validation action. + * + * @returns A hex color action. + */ +declare function hexColor(): HexColorAction; +/** + * Creates a [hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) validation action. + * + * @param message The error message. + * + * @returns A hex color action. + */ +declare function hexColor> | undefined>(message: TMessage): HexColorAction; + +/** + * IMEI issue type. + */ +interface ImeiIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'imei'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * IMEI action type. + */ +interface ImeiAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'imei'; + /** + * The action reference. + */ + readonly reference: typeof imei; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) validation action. + * + * Formats: + * - AABBBBBBCCCCCCD + * - AA-BBBBBB-CCCCCC-D + * + * @returns An IMEI action. + */ +declare function imei(): ImeiAction; +/** + * Creates an [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) validation action. + * + * Formats: + * - AABBBBBBCCCCCCD + * - AA-BBBBBB-CCCCCC-D + * + * @param message The error message. + * + * @returns An IMEI action. + */ +declare function imei> | undefined>(message: TMessage): ImeiAction; + +/** + * Includes issue type. + */ +interface IncludesIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'includes'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The content to be included. + */ + readonly requirement: TRequirement; +} +/** + * Includes action type. + */ +interface IncludesAction, TMessage extends ErrorMessage> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'includes'; + /** + * The action reference. + */ + readonly reference: typeof includes; + /** + * The expected property. + */ + readonly expects: string; + /** + * The content to be included. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an includes validation action. + * + * @param requirement The content to be included. + * + * @returns An includes action. + */ +declare function includes>(requirement: TRequirement): IncludesAction; +/** + * Creates an includes validation action. + * + * @param requirement The content to be included. + * @param message The error message. + * + * @returns An includes action. + */ +declare function includes, const TMessage extends ErrorMessage> | undefined>(requirement: TRequirement, message: TMessage): IncludesAction; + +/** + * Integer issue type. + */ +interface IntegerIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'integer'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Integer action type. + */ +interface IntegerAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'integer'; + /** + * The action reference. + */ + readonly reference: typeof integer; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [integer](https://en.wikipedia.org/wiki/Integer) validation action. + * + * @returns An integer action. + */ +declare function integer(): IntegerAction; +/** + * Creates an [integer](https://en.wikipedia.org/wiki/Integer) validation action. + * + * @param message The error message. + * + * @returns An integer action. + */ +declare function integer> | undefined>(message: TMessage): IntegerAction; + +/** + * IP issue type. + */ +interface IpIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ip'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IP regex. + */ + readonly requirement: RegExp; +} +/** + * IP action type. + */ +interface IpAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ip'; + /** + * The action reference. + */ + readonly reference: typeof ip; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IP regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IP address](https://en.wikipedia.org/wiki/IP_address) validation action. + * + * @returns An IP action. + */ +declare function ip(): IpAction; +/** + * Creates an [IP address](https://en.wikipedia.org/wiki/IP_address) validation action. + * + * @param message The error message. + * + * @returns An IP action. + */ +declare function ip> | undefined>(message: TMessage): IpAction; + +/** + * IPv4 issue type. + */ +interface Ipv4Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ipv4'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IPv4 regex. + */ + readonly requirement: RegExp; +} +/** + * IPv4 action type. + */ +interface Ipv4Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ipv4'; + /** + * The action reference. + */ + readonly reference: typeof ipv4; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IPv4 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IPv4](https://en.wikipedia.org/wiki/IPv4) address validation action. + * + * @returns An IPv4 action. + */ +declare function ipv4(): Ipv4Action; +/** + * Creates an [IPv4](https://en.wikipedia.org/wiki/IPv4) address validation action. + * + * @param message The error message. + * + * @returns An IPv4 action. + */ +declare function ipv4> | undefined>(message: TMessage): Ipv4Action; + +/** + * IPv6 issue type. + */ +interface Ipv6Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ipv6'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IPv6 regex. + */ + readonly requirement: RegExp; +} +/** + * IPv6 action type. + */ +interface Ipv6Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ipv6'; + /** + * The action reference. + */ + readonly reference: typeof ipv6; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IPv6 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IPv6](https://en.wikipedia.org/wiki/IPv6) address validation action. + * + * @returns An IPv6 action. + */ +declare function ipv6(): Ipv6Action; +/** + * Creates an [IPv6](https://en.wikipedia.org/wiki/IPv6) address validation action. + * + * @param message The error message. + * + * @returns An IPv6 action. + */ +declare function ipv6> | undefined>(message: TMessage): Ipv6Action; + +/** + * ISO date issue type. + */ +interface IsoDateIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_date'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO date regex. + */ + readonly requirement: RegExp; +} +/** + * ISO date action type. + */ +interface IsoDateAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_date'; + /** + * The action reference. + */ + readonly reference: typeof isoDate; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO date regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO date](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-dd + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31" is valid although June has only + * 30 days. + * + * @returns An ISO date action. + */ +declare function isoDate(): IsoDateAction; +/** + * Creates an [ISO date](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-dd + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31" is valid although June has only + * 30 days. + * + * @param message The error message. + * + * @returns An ISO date action. + */ +declare function isoDate> | undefined>(message: TMessage): IsoDateAction; + +/** + * ISO date time issue type. + */ +interface IsoDateTimeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_date_time'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO date time regex. + */ + readonly requirement: RegExp; +} +/** + * ISO date time action type. + */ +interface IsoDateTimeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_date_time'; + /** + * The action reference. + */ + readonly reference: typeof isoDateTime; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO date time regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO date time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-ddThh:mm + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00" is valid although June has only + * 30 days. + * + * @returns An ISO date time action. + */ +declare function isoDateTime(): IsoDateTimeAction; +/** + * Creates an [ISO date time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-ddThh:mm + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00" is valid although June has only + * 30 days. + * + * @param message The error message. + * + * @returns An ISO date time action. + */ +declare function isoDateTime> | undefined>(message: TMessage): IsoDateTimeAction; + +/** + * ISO time issue type. + */ +interface IsoTimeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_time'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO time regex. + */ + readonly requirement: RegExp; +} +/** + * ISO time action type. + */ +interface IsoTimeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_time'; + /** + * The action reference. + */ + readonly reference: typeof isoTime; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO time regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm + * + * @returns An ISO time action. + */ +declare function isoTime(): IsoTimeAction; +/** + * Creates an [ISO time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm + * + * @param message The error message. + * + * @returns An ISO time action. + */ +declare function isoTime> | undefined>(message: TMessage): IsoTimeAction; + +/** + * ISO time second issue type. + */ +interface IsoTimeSecondIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_time_second'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO time with seconds regex. + */ + readonly requirement: RegExp; +} +/** + * ISO time second action type. + */ +interface IsoTimeSecondAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_time_second'; + /** + * The action reference. + */ + readonly reference: typeof isoTimeSecond; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO time second regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO time second](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm:ss + * + * @returns An ISO time second action. + */ +declare function isoTimeSecond(): IsoTimeSecondAction; +/** + * Creates an [ISO time second](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm:ss + * + * @param message The error message. + * + * @returns An ISO time second action. + */ +declare function isoTimeSecond> | undefined>(message: TMessage): IsoTimeSecondAction; + +/** + * ISO timestamp issue type. + */ +interface IsoTimestampIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_timestamp'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO timestamp regex. + */ + readonly requirement: RegExp; +} +/** + * ISO timestamp action type. + */ +interface IsoTimestampAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_timestamp'; + /** + * The action reference. + */ + readonly reference: typeof isoTimestamp; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO timestamp regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO timestamp](https://en.wikipedia.org/wiki/ISO_8601) validation + * action. + * + * Formats: + * - yyyy-mm-ddThh:mm:ss.sssZ + * - yyyy-mm-ddThh:mm:ss.sss±hh:mm + * - yyyy-mm-ddThh:mm:ss.sss±hhmm + * + * Hint: To support timestamps with lower or higher accuracy, the millisecond + * specification can be removed or contain up to 9 digits. + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00:00.000Z" is valid although + * June has only 30 days. + * + * @returns An ISO timestamp action. + */ +declare function isoTimestamp(): IsoTimestampAction; +/** + * Creates an [ISO timestamp](https://en.wikipedia.org/wiki/ISO_8601) validation + * action. + * + * Formats: + * - yyyy-mm-ddThh:mm:ss.sssZ + * - yyyy-mm-ddThh:mm:ss.sss±hh:mm + * - yyyy-mm-ddThh:mm:ss.sss±hhmm + * - yyyy-mm-ddThh:mm:ss.sss±hh + * + * Hint: To support timestamps with lower or higher accuracy, the millisecond + * specification can be removed or contain up to 9 digits. + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00:00.000Z" is valid although + * June has only 30 days. + * + * @param message The error message. + * + * @returns An ISO timestamp action. + */ +declare function isoTimestamp> | undefined>(message: TMessage): IsoTimestampAction; + +/** + * ISO week issue type. + */ +interface IsoWeekIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_week'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO week regex. + */ + readonly requirement: RegExp; +} +/** + * ISO week action type. + */ +interface IsoWeekAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_week'; + /** + * The action reference. + */ + readonly reference: typeof isoWeek; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO week regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO week](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-Www + * + * Hint: The regex used cannot validate the maximum number of weeks based on + * the year. For example, "2021W53" is valid although 2021 has only 52 weeks. + * + * @returns An ISO week action. + */ +declare function isoWeek(): IsoWeekAction; +/** + * Creates an [ISO week](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-Www + * + * Hint: The regex used cannot validate the maximum number of weeks based on + * the year. For example, "2021W53" is valid although 2021 has only 52 weeks. + * + * @param message The error message. + * + * @returns An ISO week action. + */ +declare function isoWeek> | undefined>(message: TMessage): IsoWeekAction; + +/** + * Length issue type. + */ +interface LengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'length'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required length. + */ + readonly requirement: TRequirement; +} +/** + * Length action type. + */ +interface LengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'length'; + /** + * The action reference. + */ + readonly reference: typeof length; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a length validation action. + * + * @param requirement The required length. + * + * @returns A length action. + */ +declare function length(requirement: TRequirement): LengthAction; +/** + * Creates a length validation action. + * + * @param requirement The required length. + * @param message The error message. + * + * @returns A length action. + */ +declare function length> | undefined>(requirement: TRequirement, message: TMessage): LengthAction; + +/** + * MAC issue type. + */ +interface MacIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The MAC regex. + */ + readonly requirement: RegExp; +} +/** + * MAC action type. + */ +interface MacAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac'; + /** + * The action reference. + */ + readonly reference: typeof mac; + /** + * The expected property. + */ + readonly expects: null; + /** + * The MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A MAC action. + */ +declare function mac(): MacAction; +/** + * Creates a [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A MAC action. + */ +declare function mac> | undefined>(message: TMessage): MacAction; + +/** + * 48-bit MAC issue type. + */ +interface Mac48Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac48'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The 48-bit MAC regex. + */ + readonly requirement: RegExp; +} +/** + * 48-bit MAC action type. + */ +interface Mac48Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac48'; + /** + * The action reference. + */ + readonly reference: typeof mac48; + /** + * The expected property. + */ + readonly expects: null; + /** + * The 48-bit MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a 48-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A 48-bit MAC action. + */ +declare function mac48(): Mac48Action; +/** + * Creates a 48-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A 48-bit MAC action. + */ +declare function mac48> | undefined>(message: TMessage): Mac48Action; + +/** + * 64-bit MAC issue type. + */ +interface Mac64Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac64'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The 64-bit MAC regex. + */ + readonly requirement: RegExp; +} +/** + * 64-bit MAC action type. + */ +interface Mac64Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac64'; + /** + * The action reference. + */ + readonly reference: typeof mac64; + /** + * The expected property. + */ + readonly expects: null; + /** + * The 64-bit MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a 64-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A 64-bit MAC action. + */ +declare function mac64(): Mac64Action; +/** + * Creates a 64-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A 64-bit MAC action. + */ +declare function mac64> | undefined>(message: TMessage): Mac64Action; + +/** + * Array action type. + */ +type ArrayAction$2 = (item: TInput[number], index: number, array: TInput) => TOutput; +/** + * Map items action type. + */ +interface MapItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'map_items'; + /** + * The action reference. + */ + readonly reference: typeof mapItems; + /** + * The map items operation. + */ + readonly operation: ArrayAction$2; +} +/** + * Creates a map items transformation action. + * + * @param operation The map items operation. + * + * @returns A map items action. + */ +declare function mapItems(operation: ArrayAction$2): MapItemsAction; + +/** + * Max bytes issue type. + */ +interface MaxBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_bytes'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum bytes. + */ + readonly requirement: TRequirement; +} +/** + * Max bytes action type. + */ +interface MaxBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_bytes'; + /** + * The action reference. + */ + readonly reference: typeof maxBytes; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The maximum bytes. + * + * @returns A max bytes action. + */ +declare function maxBytes(requirement: TRequirement): MaxBytesAction; +/** + * Creates a max [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The maximum bytes. + * @param message The error message. + * + * @returns A max bytes action. + */ +declare function maxBytes> | undefined>(requirement: TRequirement, message: TMessage): MaxBytesAction; + +/** + * Max length issue type. + */ +interface MaxLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_length'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum length. + */ + readonly requirement: TRequirement; +} +/** + * Max length action type. + */ +interface MaxLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_length'; + /** + * The action reference. + */ + readonly reference: typeof maxLength; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max length validation action. + * + * @param requirement The maximum length. + * + * @returns A max length action. + */ +declare function maxLength(requirement: TRequirement): MaxLengthAction; +/** + * Creates a max length validation action. + * + * @param requirement The maximum length. + * @param message The error message. + * + * @returns A max length action. + */ +declare function maxLength> | undefined>(requirement: TRequirement, message: TMessage): MaxLengthAction; + +/** + * Max size issue type. + */ +interface MaxSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_size'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum size. + */ + readonly requirement: TRequirement; +} +/** + * Max size action type. + */ +interface MaxSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_size'; + /** + * The action reference. + */ + readonly reference: typeof maxSize; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max size validation action. + * + * @param requirement The maximum size. + * + * @returns A max size action. + */ +declare function maxSize(requirement: TRequirement): MaxSizeAction; +/** + * Creates a max size validation action. + * + * @param requirement The maximum size. + * @param message The error message. + * + * @returns A max size action. + */ +declare function maxSize> | undefined>(requirement: TRequirement, message: TMessage): MaxSizeAction; + +/** + * Max value issue type. + */ +interface MaxValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_value'; + /** + * The expected property. + */ + readonly expected: `<=${string}`; + /** + * The maximum value. + */ + readonly requirement: TRequirement; +} +/** + * Max value action type. + */ +interface MaxValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_value'; + /** + * The action reference. + */ + readonly reference: typeof maxValue; + /** + * The expected property. + */ + readonly expects: `<=${string}`; + /** + * The maximum value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max value validation action. + * + * @param requirement The maximum value. + * + * @returns A max value action. + */ +declare function maxValue(requirement: TRequirement): MaxValueAction; +/** + * Creates a max value validation action. + * + * @param requirement The maximum value. + * @param message The error message. + * + * @returns A max value action. + */ +declare function maxValue> | undefined>(requirement: TRequirement, message: TMessage): MaxValueAction; + +/** + * Requirement type. + */ +type Requirement = readonly `${string}/${string}`[]; +/** + * MIME type issue type. + */ +interface MimeTypeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mime_type'; + /** + * The expected input. + */ + readonly expected: string; + /** + * The received input. + */ + readonly received: `"${string}"`; + /** + * The MIME types. + */ + readonly requirement: TRequirement; +} +/** + * MIME type action type. + */ +interface MimeTypeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mime_type'; + /** + * The action reference. + */ + readonly reference: typeof mimeType; + /** + * The expected property. + */ + readonly expects: string; + /** + * The MIME types. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [MIME type](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types) validation action. + * + * @param requirement The MIME types. + * + * @returns A MIME type action. + */ +declare function mimeType(requirement: TRequirement): MimeTypeAction; +/** + * Creates a [MIME type](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types) validation action. + * + * @param requirement The MIME types. + * @param message The error message. + * + * @returns A MIME type action. + */ +declare function mimeType> | undefined>(requirement: TRequirement, message: TMessage): MimeTypeAction; + +/** + * Min bytes issue type. + */ +interface MinBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_bytes'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum bytes. + */ + readonly requirement: TRequirement; +} +/** + * Min bytes action type. + */ +interface MinBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_bytes'; + /** + * The action reference. + */ + readonly reference: typeof minBytes; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The minimum bytes. + * + * @returns A min bytes action. + */ +declare function minBytes(requirement: TRequirement): MinBytesAction; +/** + * Creates a min [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The minimum bytes. + * @param message The error message. + * + * @returns A min bytes action. + */ +declare function minBytes> | undefined>(requirement: TRequirement, message: TMessage): MinBytesAction; + +/** + * Min length issue type. + */ +interface MinLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_length'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum length. + */ + readonly requirement: TRequirement; +} +/** + * Min length action type. + */ +interface MinLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_length'; + /** + * The action reference. + */ + readonly reference: typeof minLength; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min length validation action. + * + * @param requirement The minimum length. + * + * @returns A min length action. + */ +declare function minLength(requirement: TRequirement): MinLengthAction; +/** + * Creates a min length validation action. + * + * @param requirement The minimum length. + * @param message The error message. + * + * @returns A min length action. + */ +declare function minLength> | undefined>(requirement: TRequirement, message: TMessage): MinLengthAction; + +/** + * Min size issue type. + */ +interface MinSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_size'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum size. + */ + readonly requirement: TRequirement; +} +/** + * Min size action type. + */ +interface MinSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_size'; + /** + * The action reference. + */ + readonly reference: typeof minSize; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min size validation action. + * + * @param requirement The minimum size. + * + * @returns A min size action. + */ +declare function minSize(requirement: TRequirement): MinSizeAction; +/** + * Creates a min size validation action. + * + * @param requirement The minimum size. + * @param message The error message. + * + * @returns A min size action. + */ +declare function minSize> | undefined>(requirement: TRequirement, message: TMessage): MinSizeAction; + +/** + * Min value issue type. + */ +interface MinValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_value'; + /** + * The expected property. + */ + readonly expected: `>=${string}`; + /** + * The minimum value. + */ + readonly requirement: TRequirement; +} +/** + * Min value action type. + */ +interface MinValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_value'; + /** + * The action reference. + */ + readonly reference: typeof minValue; + /** + * The expected property. + */ + readonly expects: `>=${string}`; + /** + * The minimum value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min value validation action. + * + * @param requirement The minimum value. + * + * @returns A min value action. + */ +declare function minValue(requirement: TRequirement): MinValueAction; +/** + * Creates a min value validation action. + * + * @param requirement The minimum value. + * @param message The error message. + * + * @returns A min value action. + */ +declare function minValue> | undefined>(requirement: TRequirement, message: TMessage): MinValueAction; + +/** + * Multiple of issue type. + */ +interface MultipleOfIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'multiple_of'; + /** + * The expected property. + */ + readonly expected: `%${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The divisor. + */ + readonly requirement: TRequirement; +} +/** + * Multiple of action type. + */ +interface MultipleOfAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'multiple_of'; + /** + * The action reference. + */ + readonly reference: typeof multipleOf; + /** + * The expected property. + */ + readonly expects: `%${TRequirement}`; + /** + * The divisor. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [multiple](https://en.wikipedia.org/wiki/Multiple_(mathematics)) of validation action. + * + * @param requirement The divisor. + * + * @returns A multiple of action. + */ +declare function multipleOf(requirement: TRequirement): MultipleOfAction; +/** + * Creates a [multiple](https://en.wikipedia.org/wiki/Multiple_(mathematics)) of validation action. + * + * @param requirement The divisor. + * @param message The error message. + * + * @returns A multiple of action. + */ +declare function multipleOf> | undefined>(requirement: TRequirement, message: TMessage): MultipleOfAction; + +/** + * Non empty issue type. + */ +interface NonEmptyIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'non_empty'; + /** + * The expected input. + */ + readonly expected: '!0'; + /** + * The received input. + */ + readonly received: '0'; +} +/** + * Non empty action type. + */ +interface NonEmptyAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'non_empty'; + /** + * The action reference. + */ + readonly reference: typeof nonEmpty; + /** + * The expected property. + */ + readonly expects: '!0'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non-empty validation action. + * + * @returns A non-empty action. + */ +declare function nonEmpty(): NonEmptyAction; +/** + * Creates a non-empty validation action. + * + * @param message The error message. + * + * @returns A non-empty action. + */ +declare function nonEmpty> | undefined>(message: TMessage): NonEmptyAction; + +/** + * Normalize form type. + */ +type NormalizeForm = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'; +/** + * Normalize action type. + */ +interface NormalizeAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'normalize'; + /** + * The action reference. + */ + readonly reference: typeof normalize; + /** + * The normalization form. + */ + readonly form: TForm; +} +/** + * Creates a normalize transformation action. + * + * @returns A normalize action. + */ +declare function normalize(): NormalizeAction; +/** + * Creates a normalize transformation action. + * + * @param form The normalization form. + * + * @returns A normalize action. + */ +declare function normalize(form: TForm): NormalizeAction; + +/** + * Not bytes issue type. + */ +interface NotBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_bytes'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The not required bytes. + */ + readonly requirement: TRequirement; +} +/** + * Not bytes action type. + */ +interface NotBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_bytes'; + /** + * The action reference. + */ + readonly reference: typeof notBytes; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The not required bytes. + * + * @returns A not bytes action. + */ +declare function notBytes(requirement: TRequirement): NotBytesAction; +/** + * Creates a not [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The not required bytes. + * @param message The error message. + * + * @returns A not bytes action. + */ +declare function notBytes> | undefined>(requirement: TRequirement, message: TMessage): NotBytesAction; + +/** + * Not length issue type. + */ +interface NotLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_length'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${TRequirement}`; + /** + * The not required length. + */ + readonly requirement: TRequirement; +} +/** + * Not length action type. + */ +interface NotLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_length'; + /** + * The action reference. + */ + readonly reference: typeof notLength; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not length validation action. + * + * @param requirement The not required length. + * + * @returns A not length action. + */ +declare function notLength(requirement: TRequirement): NotLengthAction; +/** + * Creates a not length validation action. + * + * @param requirement The not required length. + * @param message The error message. + * + * @returns A not length action. + */ +declare function notLength> | undefined>(requirement: TRequirement, message: TMessage): NotLengthAction; + +/** + * Not size issue type. + */ +interface NotSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_size'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${TRequirement}`; + /** + * The not required size. + */ + readonly requirement: TRequirement; +} +/** + * Not size action type. + */ +interface NotSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_size'; + /** + * The action reference. + */ + readonly reference: typeof notSize; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not size validation action. + * + * @param requirement The not required size. + * + * @returns A not size action. + */ +declare function notSize(requirement: TRequirement): NotSizeAction; +/** + * Creates a not size validation action. + * + * @param requirement The not required size. + * @param message The error message. + * + * @returns A not size action. + */ +declare function notSize> | undefined>(requirement: TRequirement, message: TMessage): NotSizeAction; + +/** + * Not value issue type. + */ +interface NotValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_value'; + /** + * The expected property. + */ + readonly expected: `!${string}`; + /** + * The not required value. + */ + readonly requirement: TRequirement; +} +/** + * Not value action type. + */ +interface NotValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_value'; + /** + * The action reference. + */ + readonly reference: typeof notValue; + /** + * The expected property. + */ + readonly expects: `!${string}`; + /** + * The not required value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not value validation action. + * + * @param requirement The not required value. + * + * @returns A not value action. + */ +declare function notValue(requirement: TRequirement): NotValueAction; +/** + * Creates a not value validation action. + * + * @param requirement The not required value. + * @param message The error message. + * + * @returns A not value action. + */ +declare function notValue> | undefined>(requirement: TRequirement, message: TMessage): NotValueAction; + +/** + * Octal issue type. + */ +interface OctalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'octal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The octal regex. + */ + readonly requirement: RegExp; +} +/** + * Octal action type. + */ +interface OctalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'octal'; + /** + * The action reference. + */ + readonly reference: typeof octal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The octal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [octal](https://en.wikipedia.org/wiki/Octal) validation action. + * + * @returns An octal action. + */ +declare function octal(): OctalAction; +/** + * Creates an [octal](https://en.wikipedia.org/wiki/Octal) validation action. + * + * @param message The error message. + * + * @returns An octal action. + */ +declare function octal> | undefined>(message: TMessage): OctalAction; + +/** + * Partial input type. + */ +type PartialInput = Record | ArrayLike; +/** + * Partial check issue type. + */ +interface PartialCheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'partial_check'; + /** + * The expected input. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; +} + +/** + * Partial check action type. + */ +interface PartialCheckAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'partial_check'; + /** + * The action reference. + */ + readonly reference: typeof partialCheck; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TSelection) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * + * @returns A partial check action. + */ +declare function partialCheck[], const TSelection extends DeepPickN>(pathList: TPathList, requirement: (input: TSelection) => boolean): PartialCheckAction; +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * @param message The error message. + * + * @returns A partial check action. + */ +declare function partialCheck[], const TSelection extends DeepPickN, const TMessage extends ErrorMessage> | undefined>(pathList: TPathList, requirement: (input: TSelection) => boolean, message: TMessage): PartialCheckAction; + +/** + * Partial check action async type. + */ +interface PartialCheckActionAsync> | undefined> extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'partial_check'; + /** + * The action reference. + */ + readonly reference: typeof partialCheckAsync; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TSelection) => MaybePromise; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * + * @returns A partial check action. + */ +declare function partialCheckAsync[], const TSelection extends DeepPickN>(pathList: TPathList, requirement: (input: TSelection) => MaybePromise): PartialCheckActionAsync; +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * @param message The error message. + * + * @returns A partial check action. + */ +declare function partialCheckAsync[], const TSelection extends DeepPickN, const TMessage extends ErrorMessage> | undefined>(pathList: TPathList, requirement: (input: TSelection) => MaybePromise, message: TMessage): PartialCheckActionAsync; + +/** + * Raw check issue type. + */ +interface RawCheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'raw_check'; +} +/** + * Issue info type. + */ +interface IssueInfo$1 { + label?: string; + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; +} +/** + * Add issue type. + */ +type AddIssue$1 = (info?: IssueInfo$1) => void; +/** + * Context type. + */ +interface Context$2 { + readonly dataset: Dataset>; + readonly config: Config>; + readonly addIssue: AddIssue$1; +} + +/** + * Raw check action type. + */ +interface RawCheckAction extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'raw_check'; + /** + * The action reference. + */ + readonly reference: typeof rawCheck; + /** + * The expected property. + */ + readonly expects: null; +} +/** + * Creates a raw check validation action. + * + * @param action The validation action. + * + * @returns A raw check action. + */ +declare function rawCheck(action: (context: Context$2) => void): RawCheckAction; + +/** + * Raw check action async type. + */ +interface RawCheckActionAsync extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'raw_check'; + /** + * The action reference. + */ + readonly reference: typeof rawCheckAsync; + /** + * The expected property. + */ + readonly expects: null; +} +/** + * Creates a raw check validation action. + * + * @param action The validation action. + * + * @returns A raw check action. + */ +declare function rawCheckAsync(action: (context: Context$2) => MaybePromise): RawCheckActionAsync; + +/** + * Raw transform issue type. + */ +interface RawTransformIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'transformation'; + /** + * The issue type. + */ + readonly type: 'raw_transform'; +} +/** + * Issue info type. + */ +interface IssueInfo { + label?: string; + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; +} +/** + * Add issue type. + */ +type AddIssue = (info?: IssueInfo) => void; +/** + * Context type. + */ +interface Context$1 { + readonly dataset: TypedDataset; + readonly config: Config>; + readonly addIssue: AddIssue; + readonly NEVER: never; +} + +/** + * Raw transform action type. + */ +interface RawTransformAction extends BaseTransformation> { + /** + * The action type. + */ + readonly type: 'raw_transform'; + /** + * The action reference. + */ + readonly reference: typeof rawTransform; +} +/** + * Creates a raw transformation action. + * + * @param action The transformation action. + * + * @returns A raw transform action. + */ +declare function rawTransform(action: (context: Context$1) => TOutput): RawTransformAction; + +/** + * Raw transform action async type. + */ +interface RawTransformActionAsync extends BaseTransformationAsync> { + /** + * The action type. + */ + readonly type: 'raw_transform'; + /** + * The action reference. + */ + readonly reference: typeof rawTransformAsync; +} +/** + * Creates a raw transformation action. + * + * @param action The transformation action. + * + * @returns A raw transform action. + */ +declare function rawTransformAsync(action: (context: Context$1) => MaybePromise): RawTransformActionAsync; + +/** + * Readonly action type. + */ +interface ReadonlyAction extends BaseTransformation, never> { + /** + * The action type. + */ + readonly type: 'readonly'; + /** + * The action reference. + */ + readonly reference: typeof readonly; +} +/** + * Creates a readonly transformation action. + * + * @returns A readonly action. + */ +declare function readonly(): ReadonlyAction; + +/** + * Array action type. + */ +type ArrayAction$1 = (output: TOutput, item: TInput[number], index: number, array: TInput) => TOutput; +/** + * Reduce items action type. + */ +interface ReduceItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'reduce_items'; + /** + * The action reference. + */ + readonly reference: typeof reduceItems; + /** + * The reduce items operation. + */ + readonly operation: ArrayAction$1; + /** + * The initial value. + */ + readonly initial: TOutput; +} +/** + * Creates a reduce items transformation action. + * + * @param operation The reduce items operation. + * @param initial The initial value. + * + * @returns A reduce items action. + */ +declare function reduceItems(operation: ArrayAction$1, initial: TOutput): ReduceItemsAction; + +/** + * Regex issue type. + */ +interface RegexIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'regex'; + /** + * The expected input. + */ + readonly expected: string; + /** + * The received input. + */ + readonly received: `"${string}"`; + /** + * The regex pattern. + */ + readonly requirement: RegExp; +} +/** + * Regex action type. + */ +interface RegexAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'regex'; + /** + * The action reference. + */ + readonly reference: typeof regex; + /** + * The expected property. + */ + readonly expects: string; + /** + * The regex pattern. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [regex](https://en.wikipedia.org/wiki/Regular_expression) validation action. + * + * @param requirement The regex pattern. + * + * @returns A regex action. + */ +declare function regex(requirement: RegExp): RegexAction; +/** + * Creates a [regex](https://en.wikipedia.org/wiki/Regular_expression) validation action. + * + * @param requirement The regex pattern. + * @param message The error message. + * + * @returns A regex action. + */ +declare function regex> | undefined>(requirement: RegExp, message: TMessage): RegexAction; + +/** + * Safe integer issue type. + */ +interface SafeIntegerIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'safe_integer'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Safe integer action type. + */ +interface SafeIntegerAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'safe_integer'; + /** + * The action reference. + */ + readonly reference: typeof safeInteger; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a safe integer validation action. + * + * @returns A safe integer action. + */ +declare function safeInteger(): SafeIntegerAction; +/** + * Creates a safe integer validation action. + * + * @param message The error message. + * + * @returns A safe integer action. + */ +declare function safeInteger> | undefined>(message: TMessage): SafeIntegerAction; + +/** + * Size issue type. + */ +interface SizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'size'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required size. + */ + readonly requirement: TRequirement; +} +/** + * Size action type. + */ +interface SizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'size'; + /** + * The action reference. + */ + readonly reference: typeof size; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a size validation action. + * + * @param requirement The required size. + * + * @returns A size action. + */ +declare function size(requirement: TRequirement): SizeAction; +/** + * Creates a size validation action. + * + * @param requirement The required size. + * @param message The error message. + * + * @returns A size action. + */ +declare function size> | undefined>(requirement: TRequirement, message: TMessage): SizeAction; + +/** + * Some item issue type. + */ +interface SomeItemIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'some_item'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Some item action type. + */ +interface SomeItemAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'some_item'; + /** + * The action reference. + */ + readonly reference: typeof someItem; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a some item validation action. + * + * @param requirement The validation function. + * + * @returns A some item action. + */ +declare function someItem(requirement: ArrayRequirement): SomeItemAction; +/** + * Creates a some item validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A some item action. + */ +declare function someItem> | undefined>(requirement: ArrayRequirement, message: TMessage): SomeItemAction; + +/** + * Array action type. + */ +type ArrayAction = (itemA: TInput[number], itemB: TInput[number]) => number; +/** + * Sort items action type. + */ +interface SortItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'sort_items'; + /** + * The action reference. + */ + readonly reference: typeof sortItems; + /** + * The sort items operation. + */ + readonly operation: ArrayAction | undefined; +} +/** + * Creates a sort items transformation action. + * + * @param operation The sort items operation. + * + * @returns A sort items action. + */ +declare function sortItems(operation?: ArrayAction): SortItemsAction; + +/** + * Starts with issue type. + */ +interface StartsWithIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'starts_with'; + /** + * The expected property. + */ + readonly expected: `"${TRequirement}"`; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The start string. + */ + readonly requirement: TRequirement; +} +/** + * Starts with action type. + */ +interface StartsWithAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'starts_with'; + /** + * The action reference. + */ + readonly reference: typeof startsWith; + /** + * The expected property. + */ + readonly expects: `"${TRequirement}"`; + /** + * The start string. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a starts with validation action. + * + * @param requirement The start string. + * + * @returns A starts with action. + */ +declare function startsWith(requirement: TRequirement): StartsWithAction; +/** + * Creates a starts with validation action. + * + * @param requirement The start string. + * @param message The error message. + * + * @returns A starts with action. + */ +declare function startsWith> | undefined>(requirement: TRequirement, message: TMessage): StartsWithAction; + +/** + * To lower case action type. + */ +interface ToLowerCaseAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_lower_case'; + /** + * The action reference. + */ + readonly reference: typeof toLowerCase; +} +/** + * Creates a to lower case transformation action. + * + * @returns A to lower case action. + */ +declare function toLowerCase(): ToLowerCaseAction; + +/** + * To max value action type. + */ +interface ToMaxValueAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_max_value'; + /** + * The action reference. + */ + readonly reference: typeof toMaxValue; + /** + * The maximum value. + */ + readonly requirement: TRequirement; +} +/** + * Creates a to max value transformation action. + * + * @param requirement The maximum value. + * + * @returns A to max value action. + */ +declare function toMaxValue(requirement: TRequirement): ToMaxValueAction; + +/** + * To min value action type. + */ +interface ToMinValueAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_min_value'; + /** + * The action reference. + */ + readonly reference: typeof toMinValue; + /** + * The minimum value. + */ + readonly requirement: TRequirement; +} +/** + * Creates a to min value transformation action. + * + * @param requirement The minimum value. + * + * @returns A to min value action. + */ +declare function toMinValue(requirement: TRequirement): ToMinValueAction; + +/** + * To upper case action type. + */ +interface ToUpperCaseAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_upper_case'; + /** + * The action reference. + */ + readonly reference: typeof toUpperCase; +} +/** + * Creates a to upper case transformation action. + * + * @returns A to upper case action. + */ +declare function toUpperCase(): ToUpperCaseAction; + +/** + * Transform action type. + */ +interface TransformAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'transform'; + /** + * The action reference. + */ + readonly reference: typeof transform; + /** + * The transformation operation. + */ + readonly operation: (input: TInput) => TOutput; +} +/** + * Creates a custom transformation action. + * + * @param operation The transformation operation. + * + * @returns A transform action. + */ +declare function transform(operation: (input: TInput) => TOutput): TransformAction; + +/** + * Transform action async type. + */ +interface TransformActionAsync extends BaseTransformationAsync { + /** + * The action type. + */ + readonly type: 'transform'; + /** + * The action reference. + */ + readonly reference: typeof transformAsync; + /** + * The transformation operation. + */ + readonly operation: (input: TInput) => Promise; +} +/** + * Creates a custom transformation action. + * + * @param operation The transformation operation. + * + * @returns A transform action. + */ +declare function transformAsync(operation: (input: TInput) => Promise): TransformActionAsync; + +/** + * Trim action type. + */ +interface TrimAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim'; + /** + * The action reference. + */ + readonly reference: typeof trim; +} +/** + * Creates a trim transformation action. + * + * @returns A trim action. + */ +declare function trim(): TrimAction; + +/** + * Trim end action type. + */ +interface TrimEndAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim_end'; + /** + * The action reference. + */ + readonly reference: typeof trimEnd; +} +/** + * Creates a trim end transformation action. + * + * @returns A trim end action. + */ +declare function trimEnd(): TrimEndAction; + +/** + * Trim start action type. + */ +interface TrimStartAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim_start'; + /** + * The action reference. + */ + readonly reference: typeof trimStart; +} +/** + * Creates a trim start transformation action. + * + * @returns A trim start action. + */ +declare function trimStart(): TrimStartAction; + +/** + * ULID issue type. + */ +interface UlidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ulid'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ULID regex. + */ + readonly requirement: RegExp; +} +/** + * ULID action type. + */ +interface UlidAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ulid'; + /** + * The action reference. + */ + readonly reference: typeof ulid; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ULID regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ULID](https://github.com/ulid/spec) validation action. + * + * @returns An ULID action. + */ +declare function ulid(): UlidAction; +/** + * Creates an [ULID](https://github.com/ulid/spec) validation action. + * + * @param message The error message. + * + * @returns An ULID action. + */ +declare function ulid> | undefined>(message: TMessage): UlidAction; + +/** + * URL issue type. + */ +interface UrlIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'url'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * URL action type. + */ +interface UrlAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'url'; + /** + * The action reference. + */ + readonly reference: typeof url; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [URL](https://en.wikipedia.org/wiki/URL) validation action. + * + * Hint: The value is passed to the URL constructor to check if it is valid. + * This check is not perfect. For example, values like "abc:1234" are accepted. + * + * @returns An URL action. + */ +declare function url(): UrlAction; +/** + * Creates an [URL](https://en.wikipedia.org/wiki/URL) validation action. + * + * Hint: The value is passed to the URL constructor to check if it is valid. + * This check is not perfect. For example, values like "abc:1234" are accepted. + * + * @param message The error message. + * + * @returns An URL action. + */ +declare function url> | undefined>(message: TMessage): UrlAction; + +/** + * UUID issue type. + */ +interface UuidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'uuid'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The UUID regex. + */ + readonly requirement: RegExp; +} +/** + * UUID action type. + */ +interface UuidAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'uuid'; + /** + * The action reference. + */ + readonly reference: typeof uuid; + /** + * The expected property. + */ + readonly expects: null; + /** + * The UUID regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) validation action. + * + * @returns An UUID action. + */ +declare function uuid(): UuidAction; +/** + * Creates an [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) validation action. + * + * @param message The error message. + * + * @returns An UUID action. + */ +declare function uuid> | undefined>(message: TMessage): UuidAction; + +/** + * Value issue type. + */ +interface ValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'value'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The required value. + */ + readonly requirement: TRequirement; +} +/** + * Value action type. + */ +interface ValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'value'; + /** + * The action reference. + */ + readonly reference: typeof value; + /** + * The expected property. + */ + readonly expects: string; + /** + * The required value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a value validation action. + * + * @param requirement The required value. + * + * @returns A value action. + */ +declare function value(requirement: TRequirement): ValueAction; +/** + * Creates a value validation action. + * + * @param requirement The required value. + * @param message The error message. + * + * @returns A value action. + */ +declare function value> | undefined>(requirement: TRequirement, message: TMessage): ValueAction; + +/** + * [Base64](https://en.wikipedia.org/wiki/Base64) regex. + */ +declare const BASE64_REGEX: RegExp; +/** + * [BIC](https://en.wikipedia.org/wiki/ISO_9362) regex. + */ +declare const BIC_REGEX: RegExp; +/** + * [Cuid2](https://github.com/paralleldrive/cuid2) regex. + */ +declare const CUID2_REGEX: RegExp; +/** + * [Decimal](https://en.wikipedia.org/wiki/Decimal) regex. + */ +declare const DECIMAL_REGEX: RegExp; +/** + * Email regex. + */ +declare const EMAIL_REGEX: RegExp; +/** + * Emoji regex from [emoji-regex-xs](https://github.com/slevithan/emoji-regex-xs) v1.0.0 (MIT license). + * + * Hint: We decided against the newer `/^\p{RGI_Emoji}+$/v` regex because it is + * not supported in older runtimes and does not match all emoji. + */ +declare const EMOJI_REGEX: RegExp; +/** + * [Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) regex. + */ +declare const HEXADECIMAL_REGEX: RegExp; +/** + * [Hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) regex. + */ +declare const HEX_COLOR_REGEX: RegExp; +/** + * [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) regex. + */ +declare const IMEI_REGEX: RegExp; +/** + * [IPv4](https://en.wikipedia.org/wiki/IPv4) regex. + */ +declare const IPV4_REGEX: RegExp; +/** + * [IPv6](https://en.wikipedia.org/wiki/IPv6) regex. + */ +declare const IPV6_REGEX: RegExp; +/** + * [IP](https://en.wikipedia.org/wiki/IP_address) regex. + */ +declare const IP_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date regex. + */ +declare const ISO_DATE_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time regex. + */ +declare const ISO_DATE_TIME_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time regex. + */ +declare const ISO_TIME_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time with seconds regex. + */ +declare const ISO_TIME_SECOND_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp regex. + */ +declare const ISO_TIMESTAMP_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) week regex. + */ +declare const ISO_WEEK_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) 48 bit regex. + */ +declare const MAC48_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) 64 bit regex. + */ +declare const MAC64_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) regex. + */ +declare const MAC_REGEX: RegExp; +/** + * [Octal](https://en.wikipedia.org/wiki/Octal) regex. + */ +declare const OCTAL_REGEX: RegExp; +/** + * [ULID](https://github.com/ulid/spec) regex. + */ +declare const ULID_REGEX: RegExp; +/** + * [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) regex. + */ +declare const UUID_REGEX: RegExp; + +/** + * The global config type. + */ +type GlobalConfig = Omit, 'message'>; +/** + * Sets the global configuration. + * + * @param config The configuration. + */ +declare function setGlobalConfig(config: GlobalConfig): void; +/** + * Returns the global configuration. + * + * @param config The config to merge. + * + * @returns The configuration. + */ +declare function getGlobalConfig>(config?: Config): Config; +/** + * Deletes the global configuration. + */ +declare function deleteGlobalConfig(): void; + +/** + * Sets a global error message. + * + * @param message The error message. + * @param lang The language of the message. + */ +declare function setGlobalMessage(message: ErrorMessage>, lang?: string): void; +/** + * Returns a global error message. + * + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getGlobalMessage(lang?: string): ErrorMessage> | undefined; +/** + * Deletes a global error message. + * + * @param lang The language of the message. + */ +declare function deleteGlobalMessage(lang?: string): void; + +/** + * Sets a schema error message. + * + * @param message The error message. + * @param lang The language of the message. + */ +declare function setSchemaMessage(message: ErrorMessage>, lang?: string): void; +/** + * Returns a schema error message. + * + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getSchemaMessage(lang?: string): ErrorMessage> | undefined; +/** + * Deletes a schema error message. + * + * @param lang The language of the message. + */ +declare function deleteSchemaMessage(lang?: string): void; + +/** + * Reference type. + */ +type Reference = (...args: any[]) => BaseSchema> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync>; +/** + * Sets a specific error message. + * + * @param reference The identifier reference. + * @param message The error message. + * @param lang The language of the message. + */ +declare function setSpecificMessage(reference: TReference, message: ErrorMessage>>, lang?: string): void; +/** + * Returns a specific error message. + * + * @param reference The identifier reference. + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getSpecificMessage(reference: TReference, lang?: string): ErrorMessage>> | undefined; +/** + * Deletes a specific error message. + * + * @param reference The identifier reference. + * @param lang The language of the message. + */ +declare function deleteSpecificMessage(reference: Reference, lang?: string): void; + +/** + * Context type. + */ +type Context = BaseSchema> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync>; +/** + * Other type. + */ +interface Other { + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; + issues?: [ + BaseIssue>, + ...BaseIssue>[] + ]; +} +/** + * Adds an issue to the dataset. + * + * @param context The issue context. + * @param label The issue label. + * @param dataset The input dataset. + * @param config The configuration. + * @param other The optional props. + * + * @internal + */ +declare function _addIssue(context: TContext, label: string, dataset: Dataset>, config: Config>, other?: Other): void; + +/** + * Checks whether a string with numbers corresponds to the luhn algorithm. + * + * @param input The input to be checked. + * + * @returns Whether input is valid. + * + * @internal + */ +declare function _isLuhnAlgo(input: string): boolean; + +/** + * Disallows inherited object properties and prevents object prototype + * pollution by disallowing certain keys. + * + * @param object The object to check. + * @param key The key to check. + * + * @returns Whether the key is allowed. + * + * @internal + */ +declare function _isValidObjectKey(object: object, key: string): boolean; + +/** + * Joins multiple `expects` values with the given separator. + * + * @param values The `expects` values. + * @param separator The separator. + * + * @returns The joined `expects` property. + * + * @internal + */ +declare function _joinExpects(values: string[], separator: '&' | '|'): string; + +/** + * Stringifies an unknown input to a literal or type string. + * + * @param input The unknown input. + * + * @returns A literal or type string. + * + * @internal + */ +declare function _stringify(input: unknown): string; + +/** + * Creates an object entries definition from a list of keys and a schema. + * + * @param list A list of keys. + * @param schema The schema of the keys. + * + * @returns The object entries. + */ +declare function entriesFromList> | BaseSchemaAsync>>(list: TList, schema: TSchema): Record; + +/** + * Creates and returns the dot path of an issue if possible. + * + * @param issue The issue to get the dot path from. + * + * @returns The dot path or null. + */ +declare function getDotPath(issue: BaseIssue): string | null; +/** + * Creates and returns the dot path of an issue if possible. + * + * @param issue The issue to get the dot path from. + * + * @returns The dot path or null. + */ +declare function getDotPath> | BaseSchemaAsync>>(issue: InferIssue): IssueDotPath | null; + +/** + * A generic type guard to check the kind of an object. + * + * @param kind The kind to check for. + * @param object The object to check. + * + * @returns Whether it matches. + */ +declare function isOfKind(kind: TKind, object: TObject): object is Extract; + +/** + * A generic type guard to check the type of an object. + * + * @param type The type to check for. + * @param object The object to check. + * + * @returns Whether it matches. + */ +declare function isOfType(type: TType, object: TObject): object is Extract; + +/** + * A type guard to check if an error is a ValiError. + * + * @param error The error to check. + * + * @returns Whether its a ValiError. + */ +declare function isValiError> | BaseSchemaAsync>>(error: unknown): error is ValiError; + +/** + * A Valibot error with useful information. + */ +declare class ValiError> | BaseSchemaAsync>> extends Error { + /** + * The error issues. + */ + readonly issues: [InferIssue, ...InferIssue[]]; + /** + * Creates a Valibot error with useful information. + * + * @param issues The error issues. + */ + constructor(issues: [InferIssue, ...InferIssue[]]); +} + +export { type AnySchema, type ArrayInput, type ArrayIssue, type ArrayPathItem, type ArrayRequirement, type ArraySchema, type ArraySchemaAsync, type AwaitActionAsync, BASE64_REGEX, BIC_REGEX, type Base64Action, type Base64Issue, type BaseIssue, type BaseMetadata, type BaseSchema, type BaseSchemaAsync, type BaseTransformation, type BaseTransformationAsync, type BaseValidation, type BaseValidationAsync, type BicAction, type BicIssue, type BigintIssue, type BigintSchema, type BlobIssue, type BlobSchema, type BooleanIssue, type BooleanSchema, type Brand, type BrandAction, type BrandName, BrandSymbol, type BytesAction, type BytesIssue, CUID2_REGEX, type CheckAction, type CheckActionAsync, type CheckIssue, type CheckItemsAction, type CheckItemsIssue, type Class, type Config, type ContentInput, type ContentRequirement, type CreditCardAction, type CreditCardIssue, type Cuid2Action, type Cuid2Issue, type CustomIssue, type CustomSchema, type CustomSchemaAsync, DECIMAL_REGEX, type Dataset, type DateIssue, type DateSchema, type DecimalAction, type DecimalIssue, type DeepPickN, type Default, type DefaultAsync, type DefaultValue, type DescriptionAction, EMAIL_REGEX, EMOJI_REGEX, type EmailAction, type EmailIssue, type EmojiAction, type EmojiIssue, type EmptyAction, type EmptyIssue, type EndsWithAction, type EndsWithIssue, type Enum, type EnumIssue, type EnumSchema, type ErrorMessage, type EveryItemAction, type EveryItemIssue, type ExcludesAction, type ExcludesIssue, type Fallback, type FallbackAsync, type FileIssue, type FileSchema, type FilterItemsAction, type FindItemAction, type FiniteAction, type FiniteIssue, type FirstTupleItem, type FlatErrors, type FunctionIssue, type FunctionSchema, type GenericIssue, type GenericMetadata, type GenericSchema, type GenericSchemaAsync, type GenericTransformation, type GenericTransformationAsync, type GenericValidation, type GenericValidationAsync, type GlobalConfig, HEXADECIMAL_REGEX, HEX_COLOR_REGEX, type HashAction, type HashIssue, type HashType, type HexColorAction, type HexColorIssue, type HexadecimalAction, type HexadecimalIssue, IMEI_REGEX, IPV4_REGEX, IPV6_REGEX, IP_REGEX, ISO_DATE_REGEX, ISO_DATE_TIME_REGEX, ISO_TIMESTAMP_REGEX, ISO_TIME_REGEX, ISO_TIME_SECOND_REGEX, ISO_WEEK_REGEX, type ImeiAction, type ImeiIssue, type IncludesAction, type IncludesIssue, type InferDefault, type InferDefaults, type InferFallback, type InferFallbacks, type InferInput, type InferIntersectInput, type InferIntersectOutput, type InferIssue, type InferMapInput, type InferMapOutput, type InferNonNullableInput, type InferNonNullableIssue, type InferNonNullableOutput, type InferNonNullishInput, type InferNonNullishIssue, type InferNonNullishOutput, type InferNonOptionalInput, type InferNonOptionalIssue, type InferNonOptionalOutput, type InferNullableOutput, type InferNullishOutput, type InferObjectInput, type InferObjectIssue, type InferObjectOutput, type InferOptionalOutput, type InferOutput, type InferRecordInput, type InferRecordOutput, type InferSetInput, type InferSetOutput, type InferTupleInput, type InferTupleIssue, type InferTupleOutput, type InferVariantIssue, type InstanceIssue, type InstanceSchema, type IntegerAction, type IntegerIssue, type IntersectIssue, type IntersectOptions, type IntersectOptionsAsync, type IntersectSchema, type IntersectSchemaAsync, type IpAction, type IpIssue, type Ipv4Action, type Ipv4Issue, type Ipv6Action, type Ipv6Issue, type IsoDateAction, type IsoDateIssue, type IsoDateTimeAction, type IsoDateTimeIssue, type IsoTimeAction, type IsoTimeIssue, type IsoTimeSecondAction, type IsoTimeSecondIssue, type IsoTimestampAction, type IsoTimestampIssue, type IsoWeekAction, type IsoWeekIssue, type IssueDotPath, type IssuePathItem, type LastTupleItem, type LazySchema, type LazySchemaAsync, type LengthAction, type LengthInput, type LengthIssue, type Literal, type LiteralIssue, type LiteralSchema, type LooseObjectIssue, type LooseObjectSchema, type LooseObjectSchemaAsync, type LooseTupleIssue, type LooseTupleSchema, type LooseTupleSchemaAsync, MAC48_REGEX, MAC64_REGEX, MAC_REGEX, type Mac48Action, type Mac48Issue, type Mac64Action, type Mac64Issue, type MacAction, type MacIssue, type MapIssue, type MapItemsAction, type MapPathItem, type MapSchema, type MapSchemaAsync, type MarkOptional, type MaxBytesAction, type MaxBytesIssue, type MaxLengthAction, type MaxLengthIssue, type MaxSizeAction, type MaxSizeIssue, type MaxValueAction, type MaxValueIssue, type MaybePromise, type MaybeReadonly, type MimeTypeAction, type MimeTypeIssue, type MinBytesAction, type MinBytesIssue, type MinLengthAction, type MinLengthIssue, type MinSizeAction, type MinSizeIssue, type MinValueAction, type MinValueIssue, type MultipleOfAction, type MultipleOfIssue, type NanIssue, type NanSchema, type NeverIssue, type NeverSchema, type NoPipe, type NonEmptyAction, type NonEmptyIssue, type NonNullable$1 as NonNullable, type NonNullableIssue, type NonNullableSchema, type NonNullableSchemaAsync, type NonNullish, type NonNullishIssue, type NonNullishSchema, type NonNullishSchemaAsync, type NonOptional, type NonOptionalIssue, type NonOptionalSchema, type NonOptionalSchemaAsync, type NormalizeAction, type NormalizeForm, type NotBytesAction, type NotBytesIssue, type NotLengthAction, type NotLengthIssue, type NotSizeAction, type NotSizeIssue, type NotValueAction, type NotValueIssue, type NullIssue, type NullSchema, type NullableSchema, type NullableSchemaAsync, type NullishSchema, type NullishSchemaAsync, type NumberIssue, type NumberSchema, OCTAL_REGEX, type ObjectEntries, type ObjectEntriesAsync, type ObjectIssue, type ObjectKeys, type ObjectPathItem, type ObjectSchema, type ObjectSchemaAsync, type ObjectWithRestIssue, type ObjectWithRestSchema, type ObjectWithRestSchemaAsync, type OctalAction, type OctalIssue, type OptionalSchema, type OptionalSchemaAsync, type Parser, type ParserAsync, type PartialCheckAction, type PartialCheckActionAsync, type PartialCheckIssue, type PathKeys, type PicklistIssue, type PicklistOptions, type PicklistSchema, type PipeAction, type PipeActionAsync, type PipeItem, type PipeItemAsync, type Prettify, type PromiseIssue, type PromiseSchema, type RawCheckAction, type RawCheckActionAsync, type RawCheckIssue, type RawTransformAction, type RawTransformActionAsync, type RawTransformIssue, type ReadonlyAction, type RecordIssue, type RecordSchema, type RecordSchemaAsync, type ReduceItemsAction, type RegexAction, type RegexIssue, type SafeIntegerAction, type SafeIntegerIssue, type SafeParseResult, type SafeParser, type SafeParserAsync, type SchemaWithFallback, type SchemaWithFallbackAsync, type SchemaWithOmit, type SchemaWithPartial, type SchemaWithPartialAsync, type SchemaWithPick, type SchemaWithPipe, type SchemaWithPipeAsync, type SchemaWithRequired, type SchemaWithRequiredAsync, type SetIssue, type SetPathItem, type SetSchema, type SetSchemaAsync, type SizeAction, type SizeInput, type SizeIssue, type SomeItemAction, type SomeItemIssue, type SortItemsAction, type StartsWithAction, type StartsWithIssue, type StrictObjectIssue, type StrictObjectSchema, type StrictObjectSchemaAsync, type StrictTupleIssue, type StrictTupleSchema, type StrictTupleSchemaAsync, type StringIssue, type StringSchema, type SymbolIssue, type SymbolSchema, type ToLowerCaseAction, type ToMaxValueAction, type ToMinValueAction, type ToUpperCaseAction, type TransformAction, type TransformActionAsync, type TrimAction, type TrimEndAction, type TrimStartAction, type TupleIssue, type TupleItems, type TupleItemsAsync, type TupleSchema, type TupleSchemaAsync, type TupleWithRestIssue, type TupleWithRestSchema, type TupleWithRestSchemaAsync, type TypedDataset, ULID_REGEX, UUID_REGEX, type UlidAction, type UlidIssue, type UndefinedIssue, type UndefinedSchema, type UnionIssue, type UnionOptions, type UnionOptionsAsync, type UnionSchema, type UnionSchemaAsync, type UnionToIntersect, type UnionToTuple, type UnknownPathItem, type UnknownSchema, type UntypedDataset, type UrlAction, type UrlIssue, type UuidAction, type UuidIssue, ValiError, type ValueAction, type ValueInput, type ValueIssue, type VariantIssue, type VariantOptions, type VariantOptionsAsync, type VariantSchema, type VariantSchemaAsync, type VoidIssue, type VoidSchema, _addIssue, _isLuhnAlgo, _isValidObjectKey, _joinExpects, _stringify, any, array, arrayAsync, awaitAsync, base64, bic, bigint, blob, boolean, brand, bytes, check, checkAsync, checkItems, config, creditCard, cuid2, custom, customAsync, date, decimal, deleteGlobalConfig, deleteGlobalMessage, deleteSchemaMessage, deleteSpecificMessage, description, email, emoji, empty, endsWith, entriesFromList, enum_ as enum, enum_, everyItem, excludes, fallback, fallbackAsync, file, filterItems, findItem, finite, flatten, forward, forwardAsync, function_ as function, function_, getDefault, getDefaults, getDefaultsAsync, getDotPath, getFallback, getFallbacks, getFallbacksAsync, getGlobalConfig, getGlobalMessage, getSchemaMessage, getSpecificMessage, hash, hexColor, hexadecimal, imei, includes, instance, integer, intersect, intersectAsync, ip, ipv4, ipv6, is, isOfKind, isOfType, isValiError, isoDate, isoDateTime, isoTime, isoTimeSecond, isoTimestamp, isoWeek, keyof, lazy, lazyAsync, length, literal, looseObject, looseObjectAsync, looseTuple, looseTupleAsync, mac, mac48, mac64, map, mapAsync, mapItems, maxBytes, maxLength, maxSize, maxValue, mimeType, minBytes, minLength, minSize, minValue, multipleOf, nan, never, nonEmpty, nonNullable, nonNullableAsync, nonNullish, nonNullishAsync, nonOptional, nonOptionalAsync, normalize, notBytes, notLength, notSize, notValue, null_ as null, null_, nullable, nullableAsync, nullish, nullishAsync, number, object, objectAsync, objectWithRest, objectWithRestAsync, octal, omit, optional, optionalAsync, parse, parseAsync, parser, parserAsync, partial, partialAsync, partialCheck, partialCheckAsync, pick, picklist, pipe, pipeAsync, promise, rawCheck, rawCheckAsync, rawTransform, rawTransformAsync, readonly, record, recordAsync, reduceItems, regex, required, requiredAsync, safeInteger, safeParse, safeParseAsync, safeParser, safeParserAsync, set, setAsync, setGlobalConfig, setGlobalMessage, setSchemaMessage, setSpecificMessage, size, someItem, sortItems, startsWith, strictObject, strictObjectAsync, strictTuple, strictTupleAsync, string, symbol, toLowerCase, toMaxValue, toMinValue, toUpperCase, transform, transformAsync, trim, trimEnd, trimStart, tuple, tupleAsync, tupleWithRest, tupleWithRestAsync, ulid, undefined_ as undefined, undefined_, union, unionAsync, unknown, unwrap, url, uuid, value, variant, variantAsync, void_ as void, void_ }; diff --git a/src/libMPC/node_modules/valibot/dist/index.d.ts b/src/libMPC/node_modules/valibot/dist/index.d.ts new file mode 100644 index 0000000..0b97e53 --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.d.ts @@ -0,0 +1,12416 @@ +/** + * Any schema type. + */ +interface AnySchema extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'any'; + /** + * The schema reference. + */ + readonly reference: typeof any; + /** + * The expected property. + */ + readonly expects: 'any'; +} +/** + * Creates an any schema. + * + * Hint: This schema function exists only for completeness and is not + * recommended in practice. Instead, `unknown` should be used to accept + * unknown data. + * + * @returns An any schema. + */ +declare function any(): AnySchema; + +/** + * Array issue type. + */ +interface ArrayIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'array'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Array schema type. + */ +interface ArraySchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema[], InferOutput[], ArrayIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'array'; + /** + * The schema reference. + */ + readonly reference: typeof array; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The array item schema. + */ + readonly item: TItem; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an array schema. + * + * @param item The item schema. + * + * @returns An array schema. + */ +declare function array>>(item: TItem): ArraySchema; +/** + * Creates an array schema. + * + * @param item The item schema. + * @param message The error message. + * + * @returns An array schema. + */ +declare function array>, const TMessage extends ErrorMessage | undefined>(item: TItem, message: TMessage): ArraySchema; + +/** + * Array schema type. + */ +interface ArraySchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync[], InferOutput[], ArrayIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'array'; + /** + * The schema reference. + */ + readonly reference: typeof arrayAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The array item schema. + */ + readonly item: TItem; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an array schema. + * + * @param item The item schema. + * + * @returns An array schema. + */ +declare function arrayAsync> | BaseSchemaAsync>>(item: TItem): ArraySchemaAsync; +/** + * Creates an array schema. + * + * @param item The item schema. + * @param message The error message. + * + * @returns An array schema. + */ +declare function arrayAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(item: TItem, message: TMessage): ArraySchemaAsync; + +/** + * Bigint issue type. + */ +interface BigintIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'bigint'; + /** + * The expected property. + */ + readonly expected: 'bigint'; +} +/** + * Bigint schema type. + */ +interface BigintSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'bigint'; + /** + * The schema reference. + */ + readonly reference: typeof bigint; + /** + * The expected property. + */ + readonly expects: 'bigint'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a bigint schema. + * + * @returns A bigint schema. + */ +declare function bigint(): BigintSchema; +/** + * Creates a bigint schema. + * + * @param message The error message. + * + * @returns A bigint schema. + */ +declare function bigint | undefined>(message: TMessage): BigintSchema; + +/** + * Blob issue type. + */ +interface BlobIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'blob'; + /** + * The expected property. + */ + readonly expected: 'Blob'; +} +/** + * Blob schema type. + */ +interface BlobSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'blob'; + /** + * The schema reference. + */ + readonly reference: typeof blob; + /** + * The expected property. + */ + readonly expects: 'Blob'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a blob schema. + * + * @returns A blob schema. + */ +declare function blob(): BlobSchema; +/** + * Creates a blob schema. + * + * @param message The error message. + * + * @returns A blob schema. + */ +declare function blob | undefined>(message: TMessage): BlobSchema; + +/** + * Boolean issue type. + */ +interface BooleanIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'boolean'; + /** + * The expected property. + */ + readonly expected: 'boolean'; +} +/** + * Boolean schema type. + */ +interface BooleanSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'boolean'; + /** + * The schema reference. + */ + readonly reference: typeof boolean; + /** + * The expected property. + */ + readonly expects: 'boolean'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a boolean schema. + * + * @returns A boolean schema. + */ +declare function boolean(): BooleanSchema; +/** + * Creates a boolean schema. + * + * @param message The error message. + * + * @returns A boolean schema. + */ +declare function boolean | undefined>(message: TMessage): BooleanSchema; + +/** + * Custom issue type. + */ +interface CustomIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'custom'; + /** + * The expected property. + */ + readonly expected: 'unknown'; +} + +/** + * Check type. + */ +type Check = (input: unknown) => boolean; +/** + * Custom schema type. + */ +interface CustomSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'custom'; + /** + * The schema reference. + */ + readonly reference: typeof custom; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The type check function. + */ + readonly check: Check; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a custom schema. + * + * @param check The type check function. + * + * @returns A custom schema. + */ +declare function custom(check: Check): CustomSchema; +/** + * Creates a custom schema. + * + * @param check The type check function. + * @param message The error message. + * + * @returns A custom schema. + */ +declare function custom | undefined = ErrorMessage | undefined>(check: Check, message: TMessage): CustomSchema; + +/** + * Check async type. + */ +type CheckAsync = (input: unknown) => MaybePromise; +/** + * Custom schema async type. + */ +interface CustomSchemaAsync | undefined> extends BaseSchemaAsync { + /** + * The schema type. + */ + readonly type: 'custom'; + /** + * The schema reference. + */ + readonly reference: typeof customAsync; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The type check function. + */ + readonly check: CheckAsync; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a custom schema. + * + * @param check The type check function. + * + * @returns A custom schema. + */ +declare function customAsync(check: CheckAsync): CustomSchemaAsync; +/** + * Creates a custom schema. + * + * @param check The type check function. + * @param message The error message. + * + * @returns A custom schema. + */ +declare function customAsync | undefined = ErrorMessage | undefined>(check: CheckAsync, message: TMessage): CustomSchemaAsync; + +/** + * Date issue type. + */ +interface DateIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'date'; + /** + * The expected property. + */ + readonly expected: 'Date'; +} +/** + * Date schema type. + */ +interface DateSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'date'; + /** + * The schema reference. + */ + readonly reference: typeof date; + /** + * The expected property. + */ + readonly expects: 'Date'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a date schema. + * + * @returns A date schema. + */ +declare function date(): DateSchema; +/** + * Creates a date schema. + * + * @param message The error message. + * + * @returns A date schema. + */ +declare function date | undefined>(message: TMessage): DateSchema; + +/** + * Enum type. + */ +interface Enum { + [key: string]: string | number; +} +/** + * Enum issue type. + */ +interface EnumIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'enum'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Enum schema type. + */ +interface EnumSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'enum'; + /** + * The schema reference. + */ + readonly reference: typeof enum_; + /** + * The enum object. + */ + readonly enum: TEnum; + /** + * The enum options. + */ + readonly options: TEnum[keyof TEnum][]; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an enum schema. + * + * @param enum__ The enum object. + * + * @returns An enum schema. + */ +declare function enum_(enum__: TEnum): EnumSchema; +/** + * Creates an enum schema. + * + * @param enum__ The enum object. + * @param message The error message. + * + * @returns An enum schema. + */ +declare function enum_ | undefined>(enum__: TEnum, message: TMessage): EnumSchema; + +/** + * File issue type. + */ +interface FileIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'file'; + /** + * The expected property. + */ + readonly expected: 'File'; +} +/** + * File schema type. + */ +interface FileSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'file'; + /** + * The schema reference. + */ + readonly reference: typeof file; + /** + * The expected property. + */ + readonly expects: 'File'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a file schema. + * + * @returns A file schema. + */ +declare function file(): FileSchema; +/** + * Creates a file schema. + * + * @param message The error message. + * + * @returns A file schema. + */ +declare function file | undefined>(message: TMessage): FileSchema; + +/** + * Function issue type. + */ +interface FunctionIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'function'; + /** + * The expected property. + */ + readonly expected: 'Function'; +} +/** + * Function schema type. + */ +interface FunctionSchema | undefined> extends BaseSchema<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown, FunctionIssue> { + /** + * The schema type. + */ + readonly type: 'function'; + /** + * The schema reference. + */ + readonly reference: typeof function_; + /** + * The expected property. + */ + readonly expects: 'Function'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a function schema. + * + * @returns A function schema. + */ +declare function function_(): FunctionSchema; +/** + * Creates a function schema. + * + * @param message The error message. + * + * @returns A function schema. + */ +declare function function_ | undefined>(message: TMessage): FunctionSchema; + +/** + * Class type. + */ +type Class = new (...args: any[]) => any; +/** + * Instance issue type. + */ +interface InstanceIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'instance'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Instance schema type. + */ +interface InstanceSchema | undefined> extends BaseSchema, InstanceType, InstanceIssue> { + /** + * The schema type. + */ + readonly type: 'instance'; + /** + * The schema reference. + */ + readonly reference: typeof instance; + /** + * The class of the instance. + */ + readonly class: TClass; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an instance schema. + * + * @param class_ The class of the instance. + * + * @returns An instance schema. + */ +declare function instance(class_: TClass): InstanceSchema; +/** + * Creates an instance schema. + * + * @param class_ The class of the instance. + * @param message The error message. + * + * @returns An instance schema. + */ +declare function instance | undefined>(class_: TClass, message: TMessage): InstanceSchema; + +/** + * Intersect issue type. + */ +interface IntersectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'intersect'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Intersect options type. + */ +type IntersectOptions = MaybeReadonly>[]>; +/** + * Intersect options async type. + */ +type IntersectOptionsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Infer option type. + */ +type InferOption = BaseSchema> | BaseSchemaAsync>; +/** + * Infer intersect input type. + */ +type InferIntersectInput = TOptions extends readonly [ + InferOption, + ...infer TRest +] ? TRest extends readonly [ + InferOption, + ...InferOption[] +] ? TInput & InferIntersectInput : TInput : never; +/** + * Infer intersect output type. + */ +type InferIntersectOutput = TOptions extends readonly [ + InferOption, + ...infer TRest +] ? TRest extends readonly [ + InferOption, + ...InferOption[] +] ? TOutput & InferIntersectOutput : TOutput : never; + +/** + * Intersect schema type. + */ +interface IntersectSchema | undefined> extends BaseSchema, InferIntersectOutput, IntersectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'intersect'; + /** + * The schema reference. + */ + readonly reference: typeof intersect; + /** + * The intersect options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * + * @returns An intersect schema. + */ +declare function intersect(options: TOptions): IntersectSchema; +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * @param message The error message. + * + * @returns An intersect schema. + */ +declare function intersect | undefined>(options: TOptions, message: TMessage): IntersectSchema; + +/** + * Intersect schema async type. + */ +interface IntersectSchemaAsync | undefined> extends BaseSchemaAsync, InferIntersectOutput, IntersectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'intersect'; + /** + * The schema reference. + */ + readonly reference: typeof intersectAsync; + /** + * The intersect options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * + * @returns An intersect schema. + */ +declare function intersectAsync(options: TOptions): IntersectSchemaAsync; +/** + * Creates an intersect schema. + * + * @param options The intersect options. + * @param message The error message. + * + * @returns An intersect schema. + */ +declare function intersectAsync | undefined>(options: TOptions, message: TMessage): IntersectSchemaAsync; + +/** + * Lazy schema type. + */ +interface LazySchema>> extends BaseSchema, InferOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'lazy'; + /** + * The schema reference. + */ + readonly reference: typeof lazy; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The schema getter. + */ + readonly getter: (input: unknown) => TWrapped; +} +/** + * Creates a lazy schema. + * + * @param getter The schema getter. + * + * @returns A lazy schema. + */ +declare function lazy>>(getter: (input: unknown) => TWrapped): LazySchema; + +/** + * Lazy schema async type. + */ +interface LazySchemaAsync> | BaseSchemaAsync>> extends BaseSchemaAsync, InferOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'lazy'; + /** + * The schema reference. + */ + readonly reference: typeof lazyAsync; + /** + * The expected property. + */ + readonly expects: 'unknown'; + /** + * The schema getter. + */ + readonly getter: (input: unknown) => MaybePromise; +} +/** + * Creates a lazy schema. + * + * @param getter The schema getter. + * + * @returns A lazy schema. + */ +declare function lazyAsync> | BaseSchemaAsync>>(getter: (input: unknown) => MaybePromise): LazySchemaAsync; + +/** + * Literal type. + */ +type Literal = bigint | boolean | number | string | symbol; +/** + * Literal issue type. + */ +interface LiteralIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'literal'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Literal schema type. + */ +interface LiteralSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'literal'; + /** + * The schema reference. + */ + readonly reference: typeof literal; + /** + * The literal value. + */ + readonly literal: TLiteral; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a literal schema. + * + * @param literal_ The literal value. + * + * @returns A literal schema. + */ +declare function literal(literal_: TLiteral): LiteralSchema; +/** + * Creates a literal schema. + * + * @param literal_ The literal value. + * @param message The error message. + * + * @returns A literal schema. + */ +declare function literal | undefined>(literal_: TLiteral, message: TMessage): LiteralSchema; + +/** + * Loose object issue type. + */ +interface LooseObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'loose_object'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Loose object schema type. + */ +interface LooseObjectSchema | undefined> extends BaseSchema & { + [key: string]: unknown; +}, InferObjectOutput & { + [key: string]: unknown; +}, LooseObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'loose_object'; + /** + * The schema reference. + */ + readonly reference: typeof looseObject; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * + * @returns A loose object schema. + */ +declare function looseObject(entries: TEntries): LooseObjectSchema; +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A loose object schema. + */ +declare function looseObject | undefined>(entries: TEntries, message: TMessage): LooseObjectSchema; + +/** + * Object schema async type. + */ +interface LooseObjectSchemaAsync | undefined> extends BaseSchemaAsync & { + [key: string]: unknown; +}, InferObjectOutput & { + [key: string]: unknown; +}, LooseObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'loose_object'; + /** + * The schema reference. + */ + readonly reference: typeof looseObjectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * + * @returns A loose object schema. + */ +declare function looseObjectAsync(entries: TEntries): LooseObjectSchemaAsync; +/** + * Creates a loose object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A loose object schema. + */ +declare function looseObjectAsync | undefined>(entries: TEntries, message: TMessage): LooseObjectSchemaAsync; + +/** + * Loose tuple issue type. + */ +interface LooseTupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'loose_tuple'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Loose tuple schema type. + */ +interface LooseTupleSchema | undefined> extends BaseSchema<[ + ...InferTupleInput, + ...unknown[] +], [ + ...InferTupleOutput, + ...unknown[] +], LooseTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'loose_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof looseTuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * + * @returns A loose tuple schema. + */ +declare function looseTuple(items: TItems): LooseTupleSchema; +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A loose tuple schema. + */ +declare function looseTuple | undefined>(items: TItems, message: TMessage): LooseTupleSchema; + +/** + * Loose tuple schema async type. + */ +interface LooseTupleSchemaAsync | undefined> extends BaseSchemaAsync<[ + ...InferTupleInput, + ...unknown[] +], [ + ...InferTupleOutput, + ...unknown[] +], LooseTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'loose_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof looseTupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * + * @returns A loose tuple schema. + */ +declare function looseTupleAsync(items: TItems): LooseTupleSchemaAsync; +/** + * Creates a loose tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A loose tuple schema. + */ +declare function looseTupleAsync | undefined>(items: TItems, message: TMessage): LooseTupleSchemaAsync; + +/** + * Map issue type. + */ +interface MapIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'map'; + /** + * The expected property. + */ + readonly expected: 'Map'; +} +/** + * Infer map input type. + */ +type InferMapInput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Map, InferInput>; +/** + * Infer map output type. + */ +type InferMapOutput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Map, InferOutput>; + +/** + * Map schema type. + */ +interface MapSchema>, TValue extends BaseSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferMapOutput, MapIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'map'; + /** + * The schema reference. + */ + readonly reference: typeof map; + /** + * The expected property. + */ + readonly expects: 'Map'; + /** + * The map key schema. + */ + readonly key: TKey; + /** + * The map value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A map schema. + */ +declare function map>, const TValue extends BaseSchema>>(key: TKey, value: TValue): MapSchema; +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A map schema. + */ +declare function map>, const TValue extends BaseSchema>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): MapSchema; + +/** + * Map schema async type. + */ +interface MapSchemaAsync> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferMapOutput, MapIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'map'; + /** + * The schema reference. + */ + readonly reference: typeof mapAsync; + /** + * The expected property. + */ + readonly expects: 'Map'; + /** + * The map key schema. + */ + readonly key: TKey; + /** + * The map value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A map schema. + */ +declare function mapAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>>(key: TKey, value: TValue): MapSchemaAsync; +/** + * Creates a map schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A map schema. + */ +declare function mapAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): MapSchemaAsync; + +/** + * NaN issue type. + */ +interface NanIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'nan'; + /** + * The expected property. + */ + readonly expected: 'NaN'; +} +/** + * NaN schema type. + */ +interface NanSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'nan'; + /** + * The schema reference. + */ + readonly reference: typeof nan; + /** + * The expected property. + */ + readonly expects: 'NaN'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a NaN schema. + * + * @returns A NaN schema. + */ +declare function nan(): NanSchema; +/** + * Creates a NaN schema. + * + * @param message The error message. + * + * @returns A NaN schema. + */ +declare function nan | undefined>(message: TMessage): NanSchema; + +/** + * Never issue type. + */ +interface NeverIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'never'; + /** + * The expected property. + */ + readonly expected: 'never'; +} +/** + * Never schema type. + */ +interface NeverSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'never'; + /** + * The schema reference. + */ + readonly reference: typeof never; + /** + * The expected property. + */ + readonly expects: 'never'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a never schema. + * + * @returns A never schema. + */ +declare function never(): NeverSchema; +/** + * Creates a never schema. + * + * @param message The error message. + * + * @returns A never schema. + */ +declare function never | undefined>(message: TMessage): NeverSchema; + +/** + * Union issue type. + */ +interface UnionIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'union'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The sub issues. + */ + readonly issues?: [TSubIssue, ...TSubIssue[]]; +} + +/** + * Union options type. + */ +type UnionOptions = MaybeReadonly>[]>; +/** + * Union schema type. + */ +interface UnionSchema>> | undefined> extends BaseSchema, InferOutput, UnionIssue> | InferIssue> { + /** + * The schema type. + */ + readonly type: 'union'; + /** + * The schema reference. + */ + readonly reference: typeof union; + /** + * The union options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an union schema. + * + * @param options The union options. + * + * @returns An union schema. + */ +declare function union(options: TOptions): UnionSchema; +/** + * Creates an union schema. + * + * @param options The union options. + * @param message The error message. + * + * @returns An union schema. + */ +declare function union>> | undefined>(options: TOptions, message: TMessage): UnionSchema; + +/** + * Union options async type. + */ +type UnionOptionsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Union schema async type. + */ +interface UnionSchemaAsync>> | undefined> extends BaseSchemaAsync, InferOutput, UnionIssue> | InferIssue> { + /** + * The schema type. + */ + readonly type: 'union'; + /** + * The schema reference. + */ + readonly reference: typeof unionAsync; + /** + * The union options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an union schema. + * + * @param options The union options. + * + * @returns An union schema. + */ +declare function unionAsync(options: TOptions): UnionSchemaAsync; +/** + * Creates an union schema. + * + * @param options The union options. + * @param message The error message. + * + * @returns An union schema. + */ +declare function unionAsync>> | undefined>(options: TOptions, message: TMessage): UnionSchemaAsync; + +/** + * Non nullable issue type. + */ +interface NonNullableIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_nullable'; + /** + * The expected property. + */ + readonly expected: '!null'; +} +/** + * Infer non nullable input type. + */ +type InferNonNullableInput> | BaseSchemaAsync>> = NonNullable$1>; +/** + * Infer non nullable output type. + */ +type InferNonNullableOutput> | BaseSchemaAsync>> = NonNullable$1>; +/** + * Infer non nullable issue type. + */ +type InferNonNullableIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'null' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'null'; +}>; + +/** + * Non nullable schema type. + */ +interface NonNullableSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonNullableOutput, NonNullableIssue | InferNonNullableIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullable; + /** + * The expected property. + */ + readonly expects: '!null'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullable schema. + */ +declare function nonNullable>>(wrapped: TWrapped): NonNullableSchema; +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullable schema. + */ +declare function nonNullable>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullableSchema; + +/** + * Non nullable schema async type. + */ +interface NonNullableSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonNullableOutput, NonNullableIssue | InferNonNullableIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullableAsync; + /** + * The expected property. + */ + readonly expects: '!null'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullable schema. + */ +declare function nonNullableAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonNullableSchemaAsync; +/** + * Creates a non nullable schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullable schema. + */ +declare function nonNullableAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullableSchemaAsync; + +/** + * Non nullish issue type. + */ +interface NonNullishIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_nullish'; + /** + * The expected property. + */ + readonly expected: '(!null & !undefined)'; +} +/** + * Infer non nullish input type. + */ +type InferNonNullishInput> | BaseSchemaAsync>> = NonNullish>; +/** + * Infer non nullish output type. + */ +type InferNonNullishOutput> | BaseSchemaAsync>> = NonNullish>; +/** + * Infer non nullish issue type. + */ +type InferNonNullishIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'null' | 'undefined' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'null' | 'undefined'; +}>; + +/** + * Non nullish schema type. + */ +interface NonNullishSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonNullishOutput, NonNullishIssue | InferNonNullishIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullish; + /** + * The expected property. + */ + readonly expects: '(!null & !undefined)'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullish schema. + */ +declare function nonNullish>>(wrapped: TWrapped): NonNullishSchema; +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullish schema. + */ +declare function nonNullish>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullishSchema; + +/** + * Non nullish schema async type. + */ +interface NonNullishSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonNullishOutput, NonNullishIssue | InferNonNullishIssue> { + /** + * The schema type. + */ + readonly type: 'non_nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nonNullishAsync; + /** + * The expected property. + */ + readonly expects: '(!null & !undefined)'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non nullish schema. + */ +declare function nonNullishAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonNullishSchemaAsync; +/** + * Creates a non nullish schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non nullish schema. + */ +declare function nonNullishAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonNullishSchemaAsync; + +/** + * Non optional issue type. + */ +interface NonOptionalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'non_optional'; + /** + * The expected property. + */ + readonly expected: '!undefined'; +} +/** + * Infer non optional input type. + */ +type InferNonOptionalInput> | BaseSchemaAsync>> = NonOptional>; +/** + * Infer non optional output type. + */ +type InferNonOptionalOutput> | BaseSchemaAsync>> = NonOptional>; +/** + * Infer non optional issue type. + */ +type InferNonOptionalIssue> | BaseSchemaAsync>> = TWrapped extends UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? Exclude, { + type: 'undefined' | 'union'; +}> | UnionIssue> : Exclude, { + type: 'undefined'; +}>; + +/** + * Non optional schema type. + */ +interface NonOptionalSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferNonOptionalOutput, NonOptionalIssue | InferNonOptionalIssue> { + /** + * The schema type. + */ + readonly type: 'non_optional'; + /** + * The schema reference. + */ + readonly reference: typeof nonOptional; + /** + * The expected property. + */ + readonly expects: '!undefined'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non optional schema. + */ +declare function nonOptional>>(wrapped: TWrapped): NonOptionalSchema; +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non optional schema. + */ +declare function nonOptional>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonOptionalSchema; + +/** + * Non optional schema async type. + */ +interface NonOptionalSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferNonOptionalOutput, NonOptionalIssue | InferNonOptionalIssue> { + /** + * The schema type. + */ + readonly type: 'non_optional'; + /** + * The schema reference. + */ + readonly reference: typeof nonOptionalAsync; + /** + * The expected property. + */ + readonly expects: '!undefined'; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A non optional schema. + */ +declare function nonOptionalAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NonOptionalSchemaAsync; +/** + * Creates a non optional schema. + * + * @param wrapped The wrapped schema. + * @param message The error message. + * + * @returns A non optional schema. + */ +declare function nonOptionalAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(wrapped: TWrapped, message: TMessage): NonOptionalSchemaAsync; + +/** + * Null issue type. + */ +interface NullIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'null'; + /** + * The expected property. + */ + readonly expected: 'null'; +} +/** + * Null schema type. + */ +interface NullSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'null'; + /** + * The schema reference. + */ + readonly reference: typeof null_; + /** + * The expected property. + */ + readonly expects: 'null'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a null schema. + * + * @returns A null schema. + */ +declare function null_(): NullSchema; +/** + * Creates a null schema. + * + * @param message The error message. + * + * @returns A null schema. + */ +declare function null_ | undefined>(message: TMessage): NullSchema; + +/** + * Infer nullable output type. + */ +type InferNullableOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | null : // FIXME: For schemas that transform the input to `null`, this +NonNullable$1> | Extract, null>; + +/** + * Nullable schema type. + */ +interface NullableSchema>, TDefault extends Default> extends BaseSchema | null, InferNullableOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nullable; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullable schema. + */ +declare function nullable>>(wrapped: TWrapped): NullableSchema; +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullable schema. + */ +declare function nullable>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): NullableSchema; + +/** + * Nullable schema async type. + */ +interface NullableSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | null, InferNullableOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullable'; + /** + * The schema reference. + */ + readonly reference: typeof nullableAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullable schema. + */ +declare function nullableAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NullableSchemaAsync; +/** + * Creates a nullable schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullable schema. + */ +declare function nullableAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): NullableSchemaAsync; + +/** + * Infer nullish output type. + */ +type InferNullishOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | null | undefined : NonNullish> | Extract, null | undefined>; + +/** + * Nullish schema type. + */ +interface NullishSchema>, TDefault extends Default> extends BaseSchema | null | undefined, InferNullishOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nullish; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullish schema. + */ +declare function nullish>>(wrapped: TWrapped): NullishSchema; +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullish schema. + */ +declare function nullish>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): NullishSchema; + +/** + * Nullish schema async type. + */ +interface NullishSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | null | undefined, InferNullishOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'nullish'; + /** + * The schema reference. + */ + readonly reference: typeof nullishAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | null | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * + * @returns A nullish schema. + */ +declare function nullishAsync> | BaseSchemaAsync>>(wrapped: TWrapped): NullishSchemaAsync; +/** + * Creates a nullish schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A nullish schema. + */ +declare function nullishAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): NullishSchemaAsync; + +/** + * Number issue type. + */ +interface NumberIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'number'; + /** + * The expected property. + */ + readonly expected: 'number'; +} +/** + * Number schema type. + */ +interface NumberSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'number'; + /** + * The schema reference. + */ + readonly reference: typeof number; + /** + * The expected property. + */ + readonly expects: 'number'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a number schema. + * + * @returns A number schema. + */ +declare function number(): NumberSchema; +/** + * Creates a number schema. + * + * @param message The error message. + * + * @returns A number schema. + */ +declare function number | undefined>(message: TMessage): NumberSchema; + +/** + * Object issue type. + */ +interface ObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'object'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Object schema type. + */ +interface ObjectSchema | undefined> extends BaseSchema, InferObjectOutput, ObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'object'; + /** + * The schema reference. + */ + readonly reference: typeof object; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObject`. To + * return an issue for unknown entries, use `strictObject`. To include and + * validate unknown entries, use `objectWithRest`. + * + * @param entries The entries schema. + * + * @returns An object schema. + */ +declare function object(entries: TEntries): ObjectSchema; +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObject`. To + * return an issue for unknown entries, use `strictObject`. To include and + * validate unknown entries, use `objectWithRest`. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns An object schema. + */ +declare function object | undefined>(entries: TEntries, message: TMessage): ObjectSchema; + +/** + * Object schema async type. + */ +interface ObjectSchemaAsync | undefined> extends BaseSchemaAsync, InferObjectOutput, ObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'object'; + /** + * The schema reference. + */ + readonly reference: typeof objectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObjectAsync`. To + * return an issue for unknown entries, use `strictObjectAsync`. To include and + * validate unknown entries, use `objectWithRestAsync`. + * + * @param entries The entries schema. + * + * @returns An object schema. + */ +declare function objectAsync(entries: TEntries): ObjectSchemaAsync; +/** + * Creates an object schema. + * + * Hint: This schema removes unknown entries. The output will only include the + * entries you specify. To include unknown entries, use `looseObjectAsync`. To + * return an issue for unknown entries, use `strictObjectAsync`. To include and + * validate unknown entries, use `objectWithRestAsync`. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns An object schema. + */ +declare function objectAsync | undefined>(entries: TEntries, message: TMessage): ObjectSchemaAsync; + +/** + * Object with rest issue type. + */ +interface ObjectWithRestIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'object_with_rest'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} + +/** + * Object with rest schema type. + */ +interface ObjectWithRestSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema & { + [key: string]: InferInput; +}, InferObjectOutput & { + [key: string]: InferOutput; +}, ObjectWithRestIssue | InferObjectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'object_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof objectWithRest; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * + * @returns An object with rest schema. + */ +declare function objectWithRest>>(entries: TEntries, rest: TRest): ObjectWithRestSchema; +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns An object with rest schema. + */ +declare function objectWithRest>, const TMessage extends ErrorMessage | undefined>(entries: TEntries, rest: TRest, message: TMessage): ObjectWithRestSchema; + +/** + * Object schema async type. + */ +interface ObjectWithRestSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync & { + [key: string]: InferInput; +}, InferObjectOutput & { + [key: string]: InferOutput; +}, ObjectWithRestIssue | InferObjectIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'object_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof objectWithRestAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * + * @returns An object with rest schema. + */ +declare function objectWithRestAsync> | BaseSchemaAsync>>(entries: TEntries, rest: TRest): ObjectWithRestSchemaAsync; +/** + * Creates an object with rest schema. + * + * @param entries The entries schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns An object with rest schema. + */ +declare function objectWithRestAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(entries: TEntries, rest: TRest, message: TMessage): ObjectWithRestSchemaAsync; + +/** + * Infer optional output type. + */ +type InferOptionalOutput> | BaseSchemaAsync>, TDefault extends DefaultAsync> = [TDefault] extends [never] ? InferOutput | undefined : NonOptional> | Extract, undefined>; + +/** + * Optional schema type. + */ +interface OptionalSchema>, TDefault extends Default> extends BaseSchema | undefined, InferOptionalOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'optional'; + /** + * The schema reference. + */ + readonly reference: typeof optional; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates a optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns A optional schema. + */ +declare function optional>>(wrapped: TWrapped): OptionalSchema; +/** + * Creates a optional schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns A optional schema. + */ +declare function optional>, const TDefault extends Default>(wrapped: TWrapped, default_: TDefault): OptionalSchema; + +/** + * Optional schema async type. + */ +interface OptionalSchemaAsync> | BaseSchemaAsync>, TDefault extends DefaultAsync> extends BaseSchemaAsync | undefined, InferOptionalOutput, InferIssue> { + /** + * The schema type. + */ + readonly type: 'optional'; + /** + * The schema reference. + */ + readonly reference: typeof optionalAsync; + /** + * The expected property. + */ + readonly expects: `(${TWrapped['expects']} | undefined)`; + /** + * The wrapped schema. + */ + readonly wrapped: TWrapped; + /** + * The default value. + */ + readonly default: TDefault; +} +/** + * Creates an optional schema. + * + * @param wrapped The wrapped schema. + * + * @returns An optional schema. + */ +declare function optionalAsync> | BaseSchemaAsync>>(wrapped: TWrapped): OptionalSchemaAsync; +/** + * Creates an optional schema. + * + * @param wrapped The wrapped schema. + * @param default_ The default value. + * + * @returns An optional schema. + */ +declare function optionalAsync> | BaseSchemaAsync>, const TDefault extends DefaultAsync>(wrapped: TWrapped, default_: TDefault): OptionalSchemaAsync; + +/** + * Picklist options type. + */ +type PicklistOptions = MaybeReadonly<(string | number | bigint)[]>; +/** + * Picklist issue type. + */ +interface PicklistIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'picklist'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Picklist schema type. + */ +interface PicklistSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'picklist'; + /** + * The schema reference. + */ + readonly reference: typeof picklist; + /** + * The picklist options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a picklist schema. + * + * @param options The picklist options. + * + * @returns A picklist schema. + */ +declare function picklist(options: TOptions): PicklistSchema; +/** + * Creates a picklist schema. + * + * @param options The picklist options. + * @param message The error message. + * + * @returns A picklist schema. + */ +declare function picklist | undefined>(options: TOptions, message: TMessage): PicklistSchema; + +/** + * Promise issue type. + */ +interface PromiseIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'promise'; + /** + * The expected property. + */ + readonly expected: 'Promise'; +} +/** + * Promise schema type. + */ +interface PromiseSchema | undefined> extends BaseSchema, Promise, PromiseIssue> { + /** + * The schema type. + */ + readonly type: 'promise'; + /** + * The schema reference. + */ + readonly reference: typeof promise; + /** + * The expected property. + */ + readonly expects: 'Promise'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a promise schema. + * + * @returns A promise schema. + */ +declare function promise(): PromiseSchema; +/** + * Creates a promise schema. + * + * @param message The error message. + * + * @returns A promise schema. + */ +declare function promise | undefined>(message: TMessage): PromiseSchema; + +/** + * Changes the local configuration of a schema. + * + * @param schema The schema to configure. + * @param config The parse configuration. + * + * @returns The configured schema. + */ +declare function config> | BaseSchemaAsync>>(schema: TSchema, config: Config>): TSchema; + +/** + * Fallback type. + */ +type Fallback>> = InferOutput | ((dataset?: Dataset, InferIssue>, config?: Config>) => InferOutput); +/** + * Schema with fallback type. + */ +type SchemaWithFallback>, TFallback extends Fallback> = TSchema & { + /** + * The fallback value. + */ + readonly fallback: TFallback; +}; +/** + * Returns a fallback value as output if the input does not match the schema. + * + * @param schema The schema to catch. + * @param fallback The fallback value. + * + * @returns The passed schema. + */ +declare function fallback>, const TFallback extends Fallback>(schema: TSchema, fallback: TFallback): SchemaWithFallback; + +/** + * Fallback async type. + */ +type FallbackAsync> | BaseSchemaAsync>> = InferOutput | ((dataset?: Dataset, InferIssue>, config?: Config>) => MaybePromise>); +/** + * Schema with fallback async type. + */ +type SchemaWithFallbackAsync> | BaseSchemaAsync>, TFallback extends FallbackAsync> = Omit & { + /** + * The fallback value. + */ + readonly fallback: TFallback; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>) => Promise, InferIssue>>; +}; +/** + * Returns a fallback value as output if the input does not match the schema. + * + * @param schema The schema to catch. + * @param fallback The fallback value. + * + * @returns The passed schema. + */ +declare function fallbackAsync> | BaseSchemaAsync>, const TFallback extends FallbackAsync>(schema: TSchema, fallback: TFallback): SchemaWithFallbackAsync; + +/** + * Flat errors type. + */ +type FlatErrors> | BaseSchemaAsync> | undefined> = Prettify<{ + /** + * The root errors. + * + * Hint: The error messages of issues without a path that belong to the root + * of the schema are added to this key. + */ + readonly root?: [string, ...string[]]; + /** + * The nested errors. + * + * Hint: The error messages of issues with a path that belong to the nested + * parts of the schema and can be converted to a dot path are added to this + * key. + */ + readonly nested?: Prettify> | BaseSchemaAsync> ? IssueDotPath : string, [ + string, + ...string[] + ]>>>>; + /** + * The other errors. + * + * Hint: Some issue paths, for example for complex data types like `Set` and + * `Map`, have no key or a key that cannot be converted to a dot path. These + * error messages are added to this key. + */ + readonly other?: [string, ...string[]]; +}>; +/** + * Flatten the error messages of issues. + * + * @param issues The list of issues. + * + * @returns A flat error object. + */ +declare function flatten(issues: [BaseIssue, ...BaseIssue[]]): FlatErrors; +/** + * Flatten the error messages of issues. + * + * @param issues The list of issues. + * + * @returns A flat error object. + */ +declare function flatten> | BaseSchemaAsync>>(issues: [InferIssue, ...InferIssue[]]): FlatErrors; + +/** + * Forwards the issues of the passed validation action. + * + * @param action The validation action. + * @param pathKeys The path keys. + * + * @returns The modified action. + */ +declare function forward | ArrayLike, TIssue extends BaseIssue>(action: BaseValidation, pathKeys: PathKeys): BaseValidation; + +/** + * Forwards the issues of the passed validation action. + * + * @param action The validation action. + * @param pathKeys The path keys. + * + * @returns The modified action. + */ +declare function forwardAsync | ArrayLike, TIssue extends BaseIssue>(action: BaseValidation | BaseValidationAsync, pathKeys: PathKeys): BaseValidationAsync; + +/** + * Infer default type. + */ +type InferDefault> | BaseSchemaAsync> | NullableSchema>, unknown> | NullableSchemaAsync> | BaseSchemaAsync>, unknown> | NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>> = TSchema extends NullableSchema>, infer TDefault> | NullableSchemaAsync> | BaseSchemaAsync>, infer TDefault> | NullishSchema>, infer TDefault> | NullishSchemaAsync> | BaseSchemaAsync>, infer TDefault> | OptionalSchema>, infer TDefault> | OptionalSchemaAsync> | BaseSchemaAsync>, infer TDefault> ? [TDefault] extends [never] ? undefined : TDefault extends () => MaybePromise> ? ReturnType : TDefault : undefined; +/** + * Returns the default value of the schema. + * + * @param schema The schema to get it from. + * @param dataset The input dataset if available. + * @param config The config if available. + * + * @returns The default value. + */ +declare function getDefault> | BaseSchemaAsync>>(schema: TSchema, dataset?: Dataset, config?: Config>): InferDefault; + +/** + * Infer defaults type. + */ +type InferDefaults> | BaseSchemaAsync>> = TSchema extends LooseObjectSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> ? { + -readonly [TKey in keyof TEntries]: InferDefaults; +} : TSchema extends LooseObjectSchemaAsync | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined> ? { + -readonly [TKey in keyof TEntries]: InferDefaults; +} : TSchema extends LooseTupleSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferDefaults; +} : TSchema extends LooseTupleSchemaAsync | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchemaAsync>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferDefaults; +} : Awaited>; + +/** + * Returns the default values of the schema. + * + * Hint: The difference to `getDefault` is that for object and tuple schemas + * this function recursively returns the default values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The default values. + */ +declare function getDefaults> | LooseObjectSchema | undefined> | LooseTupleSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined>>(schema: TSchema): InferDefaults; + +/** + * Returns the default values of the schema. + * + * Hint: The difference to `getDefault` is that for object and tuple schemas + * this function recursively returns the default values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The default values. + */ +declare function getDefaultsAsync> | BaseSchemaAsync> | LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> | TupleWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined>>(schema: TSchema): Promise>; + +/** + * Infer fallback type. + */ +type InferFallback> | BaseSchemaAsync>> = TSchema extends SchemaWithFallback>, infer TFallback> | SchemaWithFallbackAsync> | BaseSchemaAsync>, infer TFallback> ? TFallback extends InferOutput ? TFallback : TFallback extends () => MaybePromise> ? ReturnType : never : undefined; +/** + * Returns the fallback value of the schema. + * + * @param schema The schema to get it from. + * @param dataset The output dataset if available. + * @param config The config if available. + * + * @returns The fallback value. + */ +declare function getFallback> | BaseSchemaAsync>>(schema: TSchema, dataset?: Dataset, InferIssue>, config?: Config>): InferFallback; + +/** + * Infer fallbacks type. + */ +type InferFallbacks> | BaseSchemaAsync>> = TSchema extends LooseObjectSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> ? { + -readonly [TKey in keyof TEntries]: InferFallbacks; +} : TSchema extends LooseObjectSchemaAsync | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined> ? { + -readonly [TKey in keyof TEntries]: InferFallbacks; +} : TSchema extends LooseTupleSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferFallbacks; +} : TSchema extends LooseTupleSchemaAsync | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchemaAsync>, ErrorMessage | undefined> ? { + -readonly [TKey in keyof TItems]: InferFallbacks; +} : Awaited>; + +/** + * Returns the fallback values of the schema. + * + * Hint: The difference to `getFallback` is that for object and tuple schemas + * this function recursively returns the fallback values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The fallback values. + */ +declare function getFallbacks> | LooseObjectSchema | undefined> | LooseTupleSchema | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictTupleSchema | undefined> | TupleSchema | undefined> | TupleWithRestSchema>, ErrorMessage | undefined>>(schema: TSchema): InferFallbacks; + +/** + * Returns the fallback values of the schema. + * + * Hint: The difference to `getFallback` is that for object and tuple schemas + * this function recursively returns the fallback values of the subschemas + * instead of `undefined`. + * + * @param schema The schema to get them from. + * + * @returns The fallback values. + */ +declare function getFallbacksAsync> | BaseSchemaAsync> | LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> | TupleWithRestSchema>, ErrorMessage | undefined> | TupleWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined>>(schema: TSchema): Promise>; + +/** + * Checks if the input matches the scheme. By using a type predicate, this + * function can be used as a type guard. + * + * @param schema The schema to be used. + * @param input The input to be tested. + * + * @returns Whether the input matches the scheme. + */ +declare function is>>(schema: TSchema, input: unknown): input is InferInput; + +/** + * Schema type. + */ +type Schema$6 = LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>; +/** + * Force tuple type. + */ +type ForceTuple = T extends [string, ...string[]] ? T : []; +/** + * Object keys type. + */ +type ObjectKeys$1 = ForceTuple>; +/** + * Creates a picklist schema of object keys. + * + * @param schema The object schema. + * + * @returns A picklist schema. + */ +declare function keyof(schema: TSchema): PicklistSchema, undefined>; +/** + * Creates a picklist schema of object keys. + * + * @param schema The object schema. + * @param message The error message. + * + * @returns A picklist schema. + */ +declare function keyof | undefined>(schema: TSchema, message: TMessage): PicklistSchema, TMessage>; + +/** + * Schema type. + */ +type Schema$5 = NoPipe | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Schema with omit type. + */ +type SchemaWithOmit> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Dataset> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Omit; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Promise> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that does not contain the + * selected entries. + * + * @param schema The schema to omit from. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function omit>(schema: TSchema, keys: TKeys): SchemaWithOmit; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parsed input. + */ +declare function parse>>(schema: TSchema, input: unknown, config?: Config>): InferOutput; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parsed input. + */ +declare function parseAsync> | BaseSchemaAsync>>(schema: TSchema, input: unknown, config?: Config>): Promise>; + +/** + * The parser type. + */ +interface Parser>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): InferOutput; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function parser>>(schema: TSchema): Parser; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function parser>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): Parser; + +/** + * The parser async type. + */ +interface ParserAsync> | BaseSchemaAsync>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): Promise>; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function parserAsync> | BaseSchemaAsync>>(schema: TSchema): ParserAsync; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function parserAsync> | BaseSchemaAsync>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): ParserAsync; + +/** + * Schema type. + */ +type Schema$4 = NoPipe | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined>>; +/** + * Partial entries type. + */ +type PartialEntries$1 = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? OptionalSchema : TEntries[TKey] : OptionalSchema; +}; +/** + * Schema with partial type. + */ +type SchemaWithPartial | undefined> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset>, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: InferIssue; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: unknown; + }, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: InferIssue; + }; +} : TSchema extends ObjectWithRestSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: InferOutput; + }, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as optional. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function partial(schema: TSchema): SchemaWithPartial; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as optional. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function partial>(schema: TSchema, keys: TKeys): SchemaWithPartial; + +/** + * Schema type. + */ +type Schema$3 = NoPipe | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Partial entries type. + */ +type PartialEntries = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? OptionalSchemaAsync : TEntries[TKey] : OptionalSchemaAsync; +}; +/** + * Schema with partial type. + */ +type SchemaWithPartialAsync | undefined> = TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise>, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: InferIssue; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: unknown; + }, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: PartialEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: InferOutput; + }, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as optional. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function partialAsync(schema: TSchema): SchemaWithPartialAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as optional. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function partialAsync>(schema: TSchema, keys: TKeys): SchemaWithPartialAsync; + +/** + * The schema type. + */ +type Schema$2 = NoPipe | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Schema with pick type. + */ +type SchemaWithPick> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise>, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Dataset> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue>>): Promise> & { + [key: string]: unknown; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue>>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue>; + }; +} : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Dataset> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync>, ErrorMessage | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: Pick; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>): Promise> & { + [key: string]: InferOutput; + }, Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: Extract, { + type: TSchema['type']; + }> | InferObjectIssue> | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that contains only the selected + * entries. + * + * @param schema The schema to pick from. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function pick>(schema: TSchema, keys: TKeys): SchemaWithPick; + +/** + * Schema with pipe type. + */ +type SchemaWithPipe>, + ...PipeItem>[] +]> = Omit, '_run' | '_types'> & { + /** + * The pipe items. + */ + readonly pipe: TPipe; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>>) => Dataset>, InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferInput>; + readonly output: InferOutput>; + readonly issue: InferIssue; + }; +}; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5, TItem6]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * @param item19 The nineteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipe>, const TItem1 extends PipeItem, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue>, const TItem19 extends PipeItem, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue>, item19: TItem19 | PipeAction, InferOutput, InferIssue>): SchemaWithPipe<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18, + TItem19 +]>; + +/** + * Schema with pipe async type. + */ +type SchemaWithPipeAsync> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] +]> = Omit, 'async' | '_run' | '_types'> & { + /** + * The pipe items. + */ + readonly pipe: TPipe; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config>>) => Promise>, InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferInput>; + readonly output: InferOutput>; + readonly issue: InferIssue; + }; +}; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3, TItem4]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[TSchema, TItem1, TItem2, TItem3, TItem4, TItem5]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18 +]>; +/** + * Adds a pipeline to a schema, that can validate and transform its input. + * + * @param schema The root schema. + * @param item1 The first pipe item. + * @param item2 The second pipe item. + * @param item3 The third pipe item. + * @param item4 The fourth pipe item. + * @param item5 The fifth pipe item. + * @param item6 The sixth pipe item. + * @param item7 The seventh pipe item. + * @param item8 The eighth pipe item. + * @param item9 The ninth pipe item. + * @param item10 The tenth pipe item. + * @param item11 The eleventh pipe item. + * @param item12 The twelfth pipe item. + * @param item13 The thirteenth pipe item. + * @param item14 The fourteenth pipe item. + * @param item15 The fifteenth pipe item. + * @param item16 The sixteenth pipe item. + * @param item17 The seventeenth pipe item. + * @param item18 The eighteenth pipe item. + * @param item19 The nineteenth pipe item. + * + * @returns A schema with a pipeline. + */ +declare function pipeAsync> | BaseSchemaAsync>, const TItem1 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem2 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem3 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem4 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem5 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem6 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem7 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem8 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem9 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem10 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem11 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem12 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem13 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem14 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem15 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem16 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem17 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem18 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>, const TItem19 extends PipeItem, unknown, BaseIssue> | PipeItemAsync, unknown, BaseIssue>>(schema: TSchema, item1: TItem1 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item2: TItem2 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item3: TItem3 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item4: TItem4 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item5: TItem5 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item6: TItem6 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item7: TItem7 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item8: TItem8 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item9: TItem9 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item10: TItem10 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item11: TItem11 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item12: TItem12 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item13: TItem13 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item14: TItem14 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item15: TItem15 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item16: TItem16 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item17: TItem17 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item18: TItem18 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>, item19: TItem19 | PipeAction, InferOutput, InferIssue> | PipeActionAsync, InferOutput, InferIssue>): SchemaWithPipeAsync<[ + TSchema, + TItem1, + TItem2, + TItem3, + TItem4, + TItem5, + TItem6, + TItem7, + TItem8, + TItem9, + TItem10, + TItem11, + TItem12, + TItem13, + TItem14, + TItem15, + TItem16, + TItem17, + TItem18, + TItem19 +]>; + +/** + * Schema type. + */ +type Schema$1 = NoPipe | undefined> | ObjectSchema | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | StrictObjectSchema | undefined>>; +/** + * Required entries type. + */ +type RequiredEntries$1 | undefined> = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? NonOptionalSchema : TEntries[TKey] : NonOptionalSchema; +}; +/** + * Schema with required type. + */ +type SchemaWithRequired | undefined, TMessage extends ErrorMessage | undefined> = TSchema extends ObjectSchema | undefined> | StrictObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset>, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends LooseObjectSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: unknown; + }, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends ObjectWithRestSchema | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries$1; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Dataset> & { + [key: string]: InferOutput; + }, NonOptionalIssue | InferIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function required(schema: TSchema): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * @param message The error message. + * + * @returns An object schema. + */ +declare function required | undefined>(schema: TSchema, message: TMessage): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function required>(schema: TSchema, keys: TKeys): SchemaWithRequired; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * @param message The error message. + * + * @returns An object schema. + */ +declare function required, const TMessage extends ErrorMessage | undefined>(schema: TSchema, keys: TKeys, message: TMessage): SchemaWithRequired; + +/** + * Schema type. + */ +type Schema = NoPipe | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync | undefined>>; +/** + * Required entries type. + */ +type RequiredEntries | undefined> = { + [TKey in keyof TEntries]: TKeys extends readonly (keyof TEntries)[] ? TKey extends TKeys[number] ? NonOptionalSchemaAsync : TEntries[TKey] : NonOptionalSchemaAsync; +}; +/** + * Schema with required type. + */ +type SchemaWithRequiredAsync | undefined, TMessage extends ErrorMessage | undefined> = TSchema extends ObjectSchemaAsync | undefined> | StrictObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise>, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput>; + readonly output: InferObjectOutput>; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends LooseObjectSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: unknown; + }, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: unknown; + }; + readonly output: InferObjectOutput> & { + [key: string]: unknown; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : TSchema extends ObjectWithRestSchemaAsync | undefined> ? Omit & { + /** + * The object entries. + */ + readonly entries: RequiredEntries; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + _run(dataset: Dataset, config: Config>): Promise> & { + [key: string]: InferOutput; + }, NonOptionalIssue | InferIssue>>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: InferObjectInput> & { + [key: string]: InferInput; + }; + readonly output: InferObjectOutput> & { + [key: string]: InferOutput; + }; + readonly issue: NonOptionalIssue | InferIssue; + }; +} : never; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * + * @returns An object schema. + */ +declare function requiredAsync(schema: TSchema): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks all entries as required. + * + * @param schema The schema to modify. + * @param message The error message. + * + * @returns An object schema. + */ +declare function requiredAsync | undefined>(schema: TSchema, message: TMessage): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * + * @returns An object schema. + */ +declare function requiredAsync>(schema: TSchema, keys: TKeys): SchemaWithRequiredAsync; +/** + * Creates a modified copy of an object schema that marks the selected entries + * as required. + * + * @param schema The schema to modify. + * @param keys The selected entries. + * @param message The error message. + * + * @returns An object schema. + */ +declare function requiredAsync, const TMessage extends ErrorMessage | undefined>(schema: TSchema, keys: TKeys, message: TMessage): SchemaWithRequiredAsync; + +/** + * Safe parse result type. + */ +type SafeParseResult> | BaseSchemaAsync>> = { + /** + * Whether is's typed. + */ + readonly typed: true; + /** + * Whether it's successful. + */ + readonly success: true; + /** + * The output value. + */ + readonly output: InferOutput; + /** + * The issues if any. + */ + readonly issues: undefined; +} | { + readonly typed: true; + readonly success: false; + readonly output: InferOutput; + readonly issues: [InferIssue, ...InferIssue[]]; +} | { + readonly typed: false; + readonly success: false; + readonly output: unknown; + readonly issues: [InferIssue, ...InferIssue[]]; +}; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parse result. + */ +declare function safeParse>>(schema: TSchema, input: unknown, config?: Config>): SafeParseResult; + +/** + * Parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param input The input to be parsed. + * @param config The parse configuration. + * + * @returns The parse result. + */ +declare function safeParseAsync> | BaseSchemaAsync>>(schema: TSchema, input: unknown, config?: Config>): Promise>; + +/** + * The safe parser type. + */ +interface SafeParser>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): SafeParseResult; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function safeParser>>(schema: TSchema): SafeParser; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function safeParser>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): SafeParser; + +/** + * The safe parser async type. + */ +interface SafeParserAsync> | BaseSchemaAsync>, TConfig extends Config> | undefined> { + /** + * Parses an unknown input based on the schema. + */ + (input: unknown): Promise>; + /** + * The schema to be used. + */ + readonly schema: TSchema; + /** + * The parser configuration. + */ + readonly config: TConfig; +} +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * + * @returns The parser function. + */ +declare function safeParserAsync> | BaseSchemaAsync>>(schema: TSchema): SafeParserAsync; +/** + * Returns a function that parses an unknown input based on a schema. + * + * @param schema The schema to be used. + * @param config The parser configuration. + * + * @returns The parser function. + */ +declare function safeParserAsync> | BaseSchemaAsync>, const TConfig extends Config> | undefined>(schema: TSchema, config: TConfig): SafeParserAsync; + +/** + * Unwraps the wrapped schema. + * + * @param schema The schema to be unwrapped. + * + * @returns The unwrapped schema. + */ +declare function unwrap>, ErrorMessage | undefined> | NonNullableSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NonNullishSchema>, ErrorMessage | undefined> | NonNullishSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NonOptionalSchema>, ErrorMessage | undefined> | NonOptionalSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | NullableSchema>, unknown> | NullableSchemaAsync> | BaseSchemaAsync>, unknown> | NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>>(schema: TSchema): TSchema['wrapped']; + +/** + * Record issue type. + */ +interface RecordIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'record'; + /** + * The expected property. + */ + readonly expected: 'Object'; +} +/** + * Is literal type. + */ +type IsLiteral = string extends TKey ? false : number extends TKey ? false : symbol extends TKey ? false : TKey extends Brand ? false : true; +/** + * Optional keys type. + */ +type OptionalKeys> = { + [TKey in keyof TObject]: IsLiteral extends true ? TKey : never; +}[keyof TObject]; +/** + * With question marks type. + * + * Hint: We mark an entry as optional if we detect that its key is a literal + * type. The reason for this is that it is not technically possible to detect + * missing literal keys without restricting the key schema to `string`, `enum` + * and `picklist`. However, if `enum` and `picklist` are used, it is better to + * use `object` with `entriesFromList` because it already covers the needed + * functionality. This decision also reduces the bundle size of `record`, + * because it only needs to check the entries of the input and not any missing + * keys. + */ +type WithQuestionMarks> = MarkOptional>; +/** + * With readonly type. + */ +type WithReadonly> | BaseSchemaAsync>, TObject extends WithQuestionMarks>> = TValue extends SchemaWithPipe<[ + BaseSchema>, + ...PipeItem>[] +]> | SchemaWithPipeAsync<[ + (BaseSchema> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] +]> ? 'readonly' extends TValue['pipe'][number]['type'] ? Readonly : TObject : TObject; +/** + * Infer record input type. + */ +type InferRecordInput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Prettify, InferInput>>>; +/** + * Infer record output type. + */ +type InferRecordOutput> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>> = Prettify, InferOutput>>>>; + +/** + * Record schema type. + */ +interface RecordSchema>, TValue extends BaseSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferRecordOutput, RecordIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'record'; + /** + * The schema reference. + */ + readonly reference: typeof record; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The record key schema. + */ + readonly key: TKey; + /** + * The record value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A record schema. + */ +declare function record>, const TValue extends BaseSchema>>(key: TKey, value: TValue): RecordSchema; +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A record schema. + */ +declare function record>, const TValue extends BaseSchema>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): RecordSchema; + +/** + * Record schema async type. + */ +interface RecordSchemaAsync> | BaseSchemaAsync>, TValue extends BaseSchema> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferRecordOutput, RecordIssue | InferIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'record'; + /** + * The schema reference. + */ + readonly reference: typeof recordAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The record key schema. + */ + readonly key: TKey; + /** + * The record value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * + * @returns A record schema. + */ +declare function recordAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>>(key: TKey, value: TValue): RecordSchemaAsync; +/** + * Creates a record schema. + * + * @param key The key schema. + * @param value The value schema. + * @param message The error message. + * + * @returns A record schema. + */ +declare function recordAsync> | BaseSchemaAsync>, const TValue extends BaseSchema> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(key: TKey, value: TValue, message: TMessage): RecordSchemaAsync; + +/** + * Set issue type. + */ +interface SetIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'set'; + /** + * The expected property. + */ + readonly expected: 'Set'; +} +/** + * Infer set input type. + */ +type InferSetInput> | BaseSchemaAsync>> = Set>; +/** + * Infer set output type. + */ +type InferSetOutput> | BaseSchemaAsync>> = Set>; + +/** + * Set schema type. + */ +interface SetSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferSetOutput, SetIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'set'; + /** + * The schema reference. + */ + readonly reference: typeof set; + /** + * The expected property. + */ + readonly expects: 'Set'; + /** + * The set value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a set schema. + * + * @param value The value schema. + * + * @returns A set schema. + */ +declare function set>>(value: TValue): SetSchema; +/** + * Creates a set schema. + * + * @param value The value schema. + * @param message The error message. + * + * @returns A set schema. + */ +declare function set>, const TMessage extends ErrorMessage | undefined>(value: TValue, message: TMessage): SetSchema; + +/** + * Set schema async type. + */ +interface SetSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferSetOutput, SetIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'set'; + /** + * The schema reference. + */ + readonly reference: typeof setAsync; + /** + * The expected property. + */ + readonly expects: 'Set'; + /** + * The set value schema. + */ + readonly value: TValue; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a set schema. + * + * @param value The value schema. + * + * @returns A set schema. + */ +declare function setAsync> | BaseSchemaAsync>>(value: TValue): SetSchemaAsync; +/** + * Creates a set schema. + * + * @param value The value schema. + * @param message The error message. + * + * @returns A set schema. + */ +declare function setAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(value: TValue, message: TMessage): SetSchemaAsync; + +/** + * Strict object issue type. + */ +interface StrictObjectIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'strict_object'; + /** + * The expected property. + */ + readonly expected: 'Object' | 'never'; +} + +/** + * Strict object schema type. + */ +interface StrictObjectSchema | undefined> extends BaseSchema, InferObjectOutput, StrictObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'strict_object'; + /** + * The schema reference. + */ + readonly reference: typeof strictObject; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * + * @returns A strict object schema. + */ +declare function strictObject(entries: TEntries): StrictObjectSchema; +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A strict object schema. + */ +declare function strictObject | undefined>(entries: TEntries, message: TMessage): StrictObjectSchema; + +/** + * Strict object schema async type. + */ +interface StrictObjectSchemaAsync | undefined> extends BaseSchemaAsync, InferObjectOutput, StrictObjectIssue | InferObjectIssue> { + /** + * The schema type. + */ + readonly type: 'strict_object'; + /** + * The schema reference. + */ + readonly reference: typeof strictObjectAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The entries schema. + */ + readonly entries: TEntries; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * + * @returns A strict object schema. + */ +declare function strictObjectAsync(entries: TEntries): StrictObjectSchemaAsync; +/** + * Creates a strict object schema. + * + * @param entries The entries schema. + * @param message The error message. + * + * @returns A strict object schema. + */ +declare function strictObjectAsync | undefined>(entries: TEntries, message: TMessage): StrictObjectSchemaAsync; + +/** + * Strict tuple issue type. + */ +interface StrictTupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'strict_tuple'; + /** + * The expected property. + */ + readonly expected: 'Array' | 'never'; +} + +/** + * Strict tuple schema type. + */ +interface StrictTupleSchema | undefined> extends BaseSchema, InferTupleOutput, StrictTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'strict_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof strictTuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * + * @returns A strict tuple schema. + */ +declare function strictTuple(items: TItems): StrictTupleSchema; +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A strict tuple schema. + */ +declare function strictTuple | undefined>(items: TItems, message: TMessage): StrictTupleSchema; + +/** + * Strict tuple schema async type. + */ +interface StrictTupleSchemaAsync | undefined> extends BaseSchemaAsync, InferTupleOutput, StrictTupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'strict_tuple'; + /** + * The schema reference. + */ + readonly reference: typeof strictTupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * + * @returns A strict tuple schema. + */ +declare function strictTupleAsync(items: TItems): StrictTupleSchemaAsync; +/** + * Creates a strict tuple schema. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A strict tuple schema. + */ +declare function strictTupleAsync | undefined>(items: TItems, message: TMessage): StrictTupleSchemaAsync; + +/** + * String issue type. + */ +interface StringIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'string'; + /** + * The expected property. + */ + readonly expected: 'string'; +} +/** + * String schema type. + */ +interface StringSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'string'; + /** + * The schema reference. + */ + readonly reference: typeof string; + /** + * The expected property. + */ + readonly expects: 'string'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a string schema. + * + * @returns A string schema. + */ +declare function string(): StringSchema; +/** + * Creates a string schema. + * + * @param message The error message. + * + * @returns A string schema. + */ +declare function string | undefined>(message: TMessage): StringSchema; + +/** + * Symbol issue type. + */ +interface SymbolIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'symbol'; + /** + * The expected property. + */ + readonly expected: 'symbol'; +} +/** + * Symbol schema type. + */ +interface SymbolSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'symbol'; + /** + * The schema reference. + */ + readonly reference: typeof symbol; + /** + * The expected property. + */ + readonly expects: 'symbol'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a symbol schema. + * + * @returns A symbol schema. + */ +declare function symbol(): SymbolSchema; +/** + * Creates a symbol schema. + * + * @param message The error message. + * + * @returns A symbol schema. + */ +declare function symbol | undefined>(message: TMessage): SymbolSchema; + +/** + * Tuple issue type. + */ +interface TupleIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'tuple'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Tuple schema type. + */ +interface TupleSchema | undefined> extends BaseSchema, InferTupleOutput, TupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'tuple'; + /** + * The schema reference. + */ + readonly reference: typeof tuple; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTuple`. To + * return an issue for unknown items, use `strictTuple`. To include and + * validate unknown items, use `tupleWithRest`. + * + * @param items The items schema. + * + * @returns A tuple schema. + */ +declare function tuple(items: TItems): TupleSchema; +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTuple`. To + * return an issue for unknown items, use `strictTuple`. To include and + * validate unknown items, use `tupleWithRest`. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A tuple schema. + */ +declare function tuple | undefined>(items: TItems, message: TMessage): TupleSchema; + +/** + * Tuple schema async type. + */ +interface TupleSchemaAsync | undefined> extends BaseSchemaAsync, InferTupleOutput, TupleIssue | InferTupleIssue> { + /** + * The schema type. + */ + readonly type: 'tuple'; + /** + * The schema reference. + */ + readonly reference: typeof tupleAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTupleAsync`. To + * return an issue for unknown items, use `strictTupleAsync`. To include and + * validate unknown items, use `tupleWithRestAsync`. + * + * @param items The items schema. + * + * @returns A tuple schema. + */ +declare function tupleAsync(items: TItems): TupleSchemaAsync; +/** + * Creates a tuple schema. + * + * Hint: This schema removes unknown items. The output will only include the + * items you specify. To include unknown items, use `looseTupleAsync`. To + * return an issue for unknown items, use `strictTupleAsync`. To include and + * validate unknown items, use `tupleWithRestAsync`. + * + * @param items The items schema. + * @param message The error message. + * + * @returns A tuple schema. + */ +declare function tupleAsync | undefined>(items: TItems, message: TMessage): TupleSchemaAsync; + +/** + * Tuple with rest issue type. + */ +interface TupleWithRestIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'tuple_with_rest'; + /** + * The expected property. + */ + readonly expected: 'Array'; +} + +/** + * Tuple with rest schema type. + */ +interface TupleWithRestSchema>, TMessage extends ErrorMessage | undefined> extends BaseSchema<[ + ...InferTupleInput, + ...InferInput[] +], [ + ...InferTupleOutput, + ...InferOutput[] +], TupleWithRestIssue | InferTupleIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'tuple_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof tupleWithRest; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRest>>(items: TItems, rest: TRest): TupleWithRestSchema; +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRest>, const TMessage extends ErrorMessage | undefined>(items: TItems, rest: TRest, message: TMessage): TupleWithRestSchema; + +/** + * Tuple with rest schema async type. + */ +interface TupleWithRestSchemaAsync> | BaseSchemaAsync>, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync<[ + ...InferTupleInput, + ...InferInput[] +], [ + ...InferTupleOutput, + ...InferOutput[] +], TupleWithRestIssue | InferTupleIssue | InferIssue> { + /** + * The schema type. + */ + readonly type: 'tuple_with_rest'; + /** + * The schema reference. + */ + readonly reference: typeof tupleWithRestAsync; + /** + * The expected property. + */ + readonly expects: 'Array'; + /** + * The items schema. + */ + readonly items: TItems; + /** + * The rest schema. + */ + readonly rest: TRest; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRestAsync> | BaseSchemaAsync>>(items: TItems, rest: TRest): TupleWithRestSchemaAsync; +/** + * Creates a tuple with rest schema. + * + * @param items The items schema. + * @param rest The rest schema. + * @param message The error message. + * + * @returns A tuple with rest schema. + */ +declare function tupleWithRestAsync> | BaseSchemaAsync>, const TMessage extends ErrorMessage | undefined>(items: TItems, rest: TRest, message: TMessage): TupleWithRestSchemaAsync; + +/** + * Undefined issue type. + */ +interface UndefinedIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'undefined'; + /** + * The expected property. + */ + readonly expected: 'undefined'; +} +/** + * Undefined schema type. + */ +interface UndefinedSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'undefined'; + /** + * The schema reference. + */ + readonly reference: typeof undefined_; + /** + * The expected property. + */ + readonly expects: 'undefined'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an undefined schema. + * + * @returns An undefined schema. + */ +declare function undefined_(): UndefinedSchema; +/** + * Creates an undefined schema. + * + * @param message The error message. + * + * @returns An undefined schema. + */ +declare function undefined_ | undefined>(message: TMessage): UndefinedSchema; + +/** + * Unknown schema type. + */ +interface UnknownSchema extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'unknown'; + /** + * The schema reference. + */ + readonly reference: typeof unknown; + /** + * The expected property. + */ + readonly expects: 'unknown'; +} +/** + * Creates a unknown schema. + * + * @returns A unknown schema. + */ +declare function unknown(): UnknownSchema; + +/** + * Variant schema type. + */ +interface VariantSchema, TMessage extends ErrorMessage | undefined> extends BaseSchema, InferOutput, VariantIssue | InferVariantIssue> { + /** + * The schema type. + */ + readonly type: 'variant'; + /** + * The schema reference. + */ + readonly reference: typeof variant; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The discriminator key. + */ + readonly key: TKey; + /** + * The variant options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * + * @returns A variant schema. + */ +declare function variant>(key: TKey, options: TOptions): VariantSchema; +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * @param message The error message. + * + * @returns An variant schema. + */ +declare function variant, const TMessage extends ErrorMessage | undefined>(key: TKey, options: TOptions, message: TMessage): VariantSchema; + +/** + * Variant schema async type. + */ +interface VariantSchemaAsync, TMessage extends ErrorMessage | undefined> extends BaseSchemaAsync, InferOutput, VariantIssue | InferVariantIssue> { + /** + * The schema type. + */ + readonly type: 'variant'; + /** + * The schema reference. + */ + readonly reference: typeof variantAsync; + /** + * The expected property. + */ + readonly expects: 'Object'; + /** + * The discriminator key. + */ + readonly key: TKey; + /** + * The variant options. + */ + readonly options: TOptions; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * + * @returns A variant schema. + */ +declare function variantAsync>(key: TKey, options: TOptions): VariantSchemaAsync; +/** + * Creates a variant schema. + * + * @param key The discriminator key. + * @param options The variant options. + * @param message The error message. + * + * @returns An variant schema. + */ +declare function variantAsync, const TMessage extends ErrorMessage | undefined>(key: TKey, options: TOptions, message: TMessage): VariantSchemaAsync; + +/** + * Variant issue type. + */ +interface VariantIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'variant'; + /** + * The expected property. + */ + readonly expected: string; +} +/** + * Variant option schema type. + */ +interface VariantOptionSchema extends BaseSchema> { + readonly type: 'variant'; + readonly reference: typeof variant; + readonly key: string; + readonly options: VariantOptions; + readonly message: ErrorMessage | undefined; +} +/** + * Variant option schema async type. + */ +interface VariantOptionSchemaAsync extends BaseSchemaAsync> { + readonly type: 'variant'; + readonly reference: typeof variantAsync; + readonly key: string; + readonly options: VariantOptionsAsync; + readonly message: ErrorMessage | undefined; +} +/** + * Variant option type. + */ +type VariantOption = LooseObjectSchema>>, ErrorMessage | undefined> | ObjectSchema>>, ErrorMessage | undefined> | ObjectWithRestSchema>>, BaseSchema>, ErrorMessage | undefined> | StrictObjectSchema>>, ErrorMessage | undefined> | VariantOptionSchema; +/** + * Variant option async type. + */ +type VariantOptionAsync = LooseObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | ObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>>, BaseSchema> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchemaAsync> | BaseSchemaAsync>>, ErrorMessage | undefined> | VariantOptionSchemaAsync; +/** + * Variant options type. + */ +type VariantOptions = MaybeReadonly[]>; +/** + * Variant options async type. + */ +type VariantOptionsAsync = MaybeReadonly<(VariantOption | VariantOptionAsync)[]>; +/** + * Infer variant issue type. + */ +type InferVariantIssue | VariantOptionsAsync> = Exclude, { + type: 'loose_object' | 'object' | 'object_with_rest'; +}>; + +/** + * Void issue type. + */ +interface VoidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'schema'; + /** + * The issue type. + */ + readonly type: 'void'; + /** + * The expected property. + */ + readonly expected: 'void'; +} +/** + * Void schema type. + */ +interface VoidSchema | undefined> extends BaseSchema { + /** + * The schema type. + */ + readonly type: 'void'; + /** + * The schema reference. + */ + readonly reference: typeof void_; + /** + * The expected property. + */ + readonly expects: 'void'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a void schema. + * + * @returns A void schema. + */ +declare function void_(): VoidSchema; +/** + * Creates a void schema. + * + * @param message The error message. + * + * @returns A void schema. + */ +declare function void_ | undefined>(message: TMessage): VoidSchema; + +/** + * Base metadata type. + */ +interface BaseMetadata { + /** + * The object kind. + */ + readonly kind: 'metadata'; + /** + * The metadata type. + */ + readonly type: string; + /** + * The metadata reference. + */ + readonly reference: (...args: any[]) => BaseMetadata; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TInput; + readonly issue: never; + }; +} +/** + * Generic metadata type. + */ +interface GenericMetadata extends BaseMetadata { +} + +/** + * Typed dataset type. + */ +interface TypedDataset> { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue; + /** + * The dataset issues. + */ + issues?: [TIssue, ...TIssue[]]; +} +/** + * Untyped dataset type. + */ +interface UntypedDataset> { + /** + * Whether is's typed. + */ + typed: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues?: [TIssue, ...TIssue[]]; +} +/** + * Dataset type. + */ +type Dataset> = TypedDataset | UntypedDataset; + +/** + * Base schema type. + */ +interface BaseSchema> { + /** + * The object kind. + */ + readonly kind: 'schema'; + /** + * The schema type. + */ + readonly type: string; + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema>; + /** + * The expected property. + */ + readonly expects: string; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config) => Dataset; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base schema async type. + */ +interface BaseSchemaAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema> | BaseSchemaAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset, config: Config) => Promise>; +} +/** + * Generic schema type. + */ +interface GenericSchema = BaseIssue> extends BaseSchema { +} +/** + * Generic schema async type. + */ +interface GenericSchemaAsync = BaseIssue> extends BaseSchemaAsync { +} + +/** + * Base transformation type. + */ +interface BaseTransformation> { + /** + * The object kind. + */ + readonly kind: 'transformation'; + /** + * The transformation type. + */ + readonly type: string; + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Transforms known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: TypedDataset, config: Config) => Dataset; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base transformation async type. + */ +interface BaseTransformationAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation | BaseTransformationAsync; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Transforms known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: TypedDataset, config: Config) => Promise>; +} +/** + * Generic transformation type. + */ +interface GenericTransformation = BaseIssue> extends BaseTransformation { +} +/** + * Generic transformation async type. + */ +interface GenericTransformationAsync = BaseIssue> extends BaseTransformationAsync { +} + +/** + * Base validation type. + */ +interface BaseValidation> { + /** + * The object kind. + */ + readonly kind: 'validation'; + /** + * The validation type. + */ + readonly type: string; + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation; + /** + * The expected property. + */ + readonly expects: string | null; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Validates known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset>, config: Config) => Dataset | TIssue>; + /** + * Input, output and issue type. + * + * @internal + */ + readonly _types?: { + readonly input: TInput; + readonly output: TOutput; + readonly issue: TIssue; + }; +} +/** + * Base validation async type. + */ +interface BaseValidationAsync> extends Omit, 'reference' | 'async' | '_run'> { + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation | BaseValidationAsync; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Validates known input. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly _run: (dataset: Dataset>, config: Config) => Promise | TIssue>>; +} +/** + * Generic validation type. + */ +interface GenericValidation = BaseIssue> extends BaseValidation { +} +/** + * Generic validation async type. + */ +interface GenericValidationAsync = BaseIssue> extends BaseValidationAsync { +} + +/** + * Infer input type. + */ +type InferInput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['input']; +/** + * Infer output type. + */ +type InferOutput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['output']; +/** + * Infer issue type. + */ +type InferIssue> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable['issue']; + +/** + * Extracts `null` from a type. + */ +type NonNullable$1 = TValue extends null ? never : TValue; +/** + * Extracts `null` and `undefined` from a type. + */ +type NonNullish = TValue extends null | undefined ? never : TValue; +/** + * Extracts `undefined` from a type. + */ +type NonOptional = TValue extends undefined ? never : TValue; +/** + * Constructs a type that is maybe readonly. + */ +type MaybeReadonly = TValue | Readonly; +/** + * Constructs a type that is maybe a promise. + */ +type MaybePromise = TValue | Promise; +/** + * Prettifies a type for better readability. + * + * Hint: This type has no effect and is only used so that TypeScript displays + * the final type in the preview instead of the utility types used. + */ +type Prettify = { + [TKey in keyof TObject]: TObject[TKey]; +} & {}; +/** + * Marks specific keys as optional. + */ +type MarkOptional = Omit & Partial>; +/** + * Extracts first tuple item. + */ +type FirstTupleItem = TTuple[0]; +/** + * Extracts last tuple item. + */ +type LastTupleItem = TTuple[TTuple extends [unknown, ...infer TRest] ? TRest['length'] : never]; +/** + * Converts union to intersection type. + */ +type UnionToIntersect = (TUnion extends any ? (arg: TUnion) => void : never) extends (arg: infer Intersect) => void ? Intersect : never; +/** + * Converts union to tuple type. + */ +type UnionToTuple = UnionToIntersect TUnion> extends () => infer TLast ? [...UnionToTuple>, TLast] : []; +/** + * Extracts tuples with path keys. + */ +type PathKeys = MaybeReadonly] : { + [TKey in keyof TValue]: TKey extends `${infer TIndex extends number}` ? [TIndex] | [TIndex, ...PathKeys] : never; +}[keyof TValue & number] : TValue extends Record ? { + [TKey in keyof TValue]: [TKey] | [TKey, ...PathKeys]; +}[keyof TValue] : never>; +/** + * Deeply picks specific keys. + * + * Hint: If this type is ever exported and accessible from the outside, it must + * be wrapped in `UnionToIntersect` to avoid invalid results. + */ +type DeepPick> = TPathKeys extends readonly [infer TPathKey, ...infer TPathRest] ? TValue extends readonly unknown[] ? number extends TValue['length'] ? TPathRest extends PathKeys ? DeepPick[] : TValue : TPathKey extends string | number ? { + [TKey in keyof TValue]: TKey extends `${TPathKey}` ? TPathRest extends PathKeys ? DeepPick : TValue[TKey] : unknown; +} : never : { + [TKey in keyof TValue as TKey extends TPathKey ? TKey : never]: TPathRest extends PathKeys ? DeepPick : TValue[TKey]; +} : never; +/** + * Deeply merges two types. + */ +type DeepMerge = TValue1 extends readonly unknown[] ? TValue2 extends readonly unknown[] ? number extends TValue1['length'] | TValue2['length'] ? DeepMerge[] : { + [TKey in keyof TValue1]: TKey extends keyof TValue2 ? unknown extends TValue1[TKey] ? TValue2[TKey] : TValue1[TKey] : never; +} : never : TValue1 extends Record ? TValue2 extends Record ? { + [TKey in keyof (TValue1 & TValue2)]: TKey extends keyof TValue1 ? TKey extends keyof TValue2 ? DeepMerge : TValue1[TKey] : TKey extends keyof TValue2 ? TValue2[TKey] : never; +} : never : TValue1 & TValue2; +/** + * Deeply picks N specific keys. + */ +type DeepPickN[]> = TPathList extends readonly [ + infer TPathKeys extends PathKeys, + ...infer TRest extends PathKeys[] +] ? TRest extends readonly [unknown, ...(readonly unknown[])] ? DeepMerge, DeepPickN> : DeepPick : TInput; + +/** + * Error message type. + */ +type ErrorMessage> = ((issue: TIssue) => string) | string; +/** + * Default type. + */ +type Default>, TInput extends null | undefined> = MaybeReadonly | TInput> | ((dataset?: Dataset, config?: Config>) => MaybeReadonly | TInput>); +/** + * Default async type. + */ +type DefaultAsync> | BaseSchemaAsync>, TInput extends null | undefined> = MaybeReadonly | TInput> | ((dataset?: Dataset, config?: Config>) => MaybePromise | TInput>>); +/** + * Default value type. + */ +type DefaultValue>, null | undefined> | DefaultAsync> | BaseSchemaAsync>, null | undefined>> = TDefault extends DefaultAsync> | BaseSchemaAsync>, infer TInput> ? TDefault extends (dataset?: Dataset, config?: Config>) => MaybePromise | TInput> ? Awaited> : TDefault : never; + +/** + * Pipe action type. + */ +type PipeAction> = BaseValidation | BaseTransformation | BaseMetadata; +/** + * Pipe action async type. + */ +type PipeActionAsync> = BaseValidationAsync | BaseTransformationAsync; +/** + * Pipe item type. + */ +type PipeItem> = BaseSchema | PipeAction; +/** + * Pipe item async type. + */ +type PipeItemAsync> = BaseSchemaAsync | PipeActionAsync; +/** + * No pipe type. + */ +type NoPipe> | BaseSchemaAsync>> = TSchema & { + pipe?: never; +}; + +/** + * Object entries type. + */ +interface ObjectEntries { + [key: string]: BaseSchema>; +} +/** + * Object entries async type. + */ +interface ObjectEntriesAsync { + [key: string]: BaseSchema> | BaseSchemaAsync>; +} +/** + * Object keys type. + */ +type ObjectKeys | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined>> = MaybeReadonly<[keyof TSchema['entries'], ...(keyof TSchema['entries'])[]]>; +/** + * Infer entries input type. + */ +type InferEntriesInput = { + -readonly [TKey in keyof TEntries]: InferInput; +}; +/** + * Infer entries output type. + */ +type InferEntriesOutput = { + -readonly [TKey in keyof TEntries]: InferOutput; +}; +/** + * Question mark schema type. + * + * TODO: Document that for simplicity and bundle size, we currently do not + * distinguish between `undefined` and missing keys when using `optional` and + * `nullish`. + */ +type QuestionMarkSchema = NullishSchema>, unknown> | NullishSchemaAsync> | BaseSchemaAsync>, unknown> | OptionalSchema>, unknown> | OptionalSchemaAsync> | BaseSchemaAsync>, unknown>; +/** + * Optional input keys type. + */ +type OptionalInputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends QuestionMarkSchema ? TKey : never; +}[keyof TEntries]; +/** + * Optional output keys type. + */ +type OptionalOutputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends QuestionMarkSchema ? [TEntries[TKey]['default']] extends [never] ? TKey : never : never; +}[keyof TEntries]; +/** + * Input with question marks type. + */ +type InputWithQuestionMarks | InferEntriesOutput> = MarkOptional>; +/** + * Output with question marks type. + */ +type OutputWithQuestionMarks | InferEntriesOutput> = MarkOptional>; +/** + * Readonly output keys type. + */ +type ReadonlyOutputKeys = { + [TKey in keyof TEntries]: TEntries[TKey] extends SchemaWithPipe<[ + BaseSchema>, + ...PipeItem>[] + ]> | SchemaWithPipeAsync<[ + (BaseSchema> | BaseSchemaAsync>), + ...(PipeItem> | PipeItemAsync>)[] + ]> ? 'readonly' extends TEntries[TKey]['pipe'][number]['type'] ? TKey : never : never; +}[keyof TEntries]; +/** + * Output with readonly type. + */ +type OutputWithReadonly>> = Readonly & Pick>>; +/** + * Infer object input type. + */ +type InferObjectInput = Prettify>>; +/** + * Infer object output type. + */ +type InferObjectOutput = Prettify>>>; +/** + * Infer object issue type. + */ +type InferObjectIssue = InferIssue; + +/** + * Tuple items type. + */ +type TupleItems = MaybeReadonly>[]>; +/** + * Tuple items async type. + */ +type TupleItemsAsync = MaybeReadonly<(BaseSchema> | BaseSchemaAsync>)[]>; +/** + * Infer tuple input type. + */ +type InferTupleInput = { + -readonly [TKey in keyof TItems]: InferInput; +}; +/** + * Infer tuple output type. + */ +type InferTupleOutput = { + -readonly [TKey in keyof TItems]: InferOutput; +}; +/** + * Infer tuple issue type. + */ +type InferTupleIssue = InferIssue; + +/** + * Array path item type. + */ +interface ArrayPathItem { + /** + * The path item type. + */ + readonly type: 'array'; + /** + * The path item origin. + */ + readonly origin: 'value'; + /** + * The path item input. + */ + readonly input: MaybeReadonly; + /** + * The path item key. + */ + readonly key: number; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Map path item type. + */ +interface MapPathItem { + /** + * The path item type. + */ + readonly type: 'map'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: Map; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Object path item type. + */ +interface ObjectPathItem { + /** + * The path item type. + */ + readonly type: 'object'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: Record; + /** + * The path item key. + */ + readonly key: string; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Set path item type. + */ +interface SetPathItem { + /** + * The path item type. + */ + readonly type: 'set'; + /** + * The path item origin. + */ + readonly origin: 'value'; + /** + * The path item input. + */ + readonly input: Set; + /** + * The path item key. + */ + readonly key: null; + /** + * The path item key. + */ + readonly value: unknown; +} +/** + * Unknown path item type. + */ +interface UnknownPathItem { + /** + * The path item type. + */ + readonly type: 'unknown'; + /** + * The path item origin. + */ + readonly origin: 'key' | 'value'; + /** + * The path item input. + */ + readonly input: unknown; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** + * Issue path item type. + * + * TODO: Document that the input of the path may be different from the input of + * the issue. + */ +type IssuePathItem = ArrayPathItem | MapPathItem | ObjectPathItem | SetPathItem | UnknownPathItem; +/** + * Base issue type. + */ +interface BaseIssue extends Config> { + /** + * The issue kind. + */ + readonly kind: 'schema' | 'validation' | 'transformation'; + /** + * The issue type. + */ + readonly type: string; + /** + * The raw input data. + */ + readonly input: TInput; + /** + * The expected property. + */ + readonly expected: string | null; + /** + * The received property. + */ + readonly received: string; + /** + * The error message. + */ + readonly message: string; + /** + * The input requirement. + */ + readonly requirement?: unknown; + /** + * The issue path. + * + * TODO: Investigate if it is possible to make the path type safe based on the + * input. + */ + readonly path?: [IssuePathItem, ...IssuePathItem[]]; + /** + * The sub issues. + */ + readonly issues?: [BaseIssue, ...BaseIssue[]]; +} +/** + * Generic issue type. + */ +interface GenericIssue extends BaseIssue { +} +/** + * Dot path type. + */ +type DotPath> | BaseSchemaAsync>> = TKey extends string | number ? `${TKey}` | `${TKey}.${IssueDotPath}` : never; +/** + * Object path type. + */ +type ObjectPath = { + [TKey in keyof TEntries]: DotPath; +}[keyof TEntries]; +/** + * Tuple keys type. + */ +type TupleKeys = Exclude; +/** + * Tuple path type. + */ +type TuplePath = { + [TKey in TupleKeys]: TItems[TKey] extends BaseSchema> | BaseSchemaAsync> ? DotPath : never; +}[TupleKeys]; +/** + * Issue dot path type. + */ +type IssueDotPath> | BaseSchemaAsync>> = TSchema extends ArraySchema | undefined> | ArraySchemaAsync | undefined> ? DotPath : TSchema extends IntersectSchema | undefined> | IntersectSchemaAsync | undefined> | UnionSchema>> | undefined> | UnionSchemaAsync>> | undefined> ? IssueDotPath : TSchema extends MapSchema | undefined> | MapSchemaAsync | undefined> | RecordSchema | undefined> | RecordSchemaAsync | undefined> ? DotPath, TValue> : TSchema extends LooseObjectSchema | undefined> | LooseObjectSchemaAsync | undefined> | ObjectSchema | undefined> | ObjectSchemaAsync | undefined> | StrictObjectSchema | undefined> | StrictObjectSchemaAsync | undefined> ? ObjectPath : TSchema extends ObjectWithRestSchema>, ErrorMessage | undefined> | ObjectWithRestSchemaAsync> | BaseSchemaAsync>, ErrorMessage | undefined> ? string : TSchema extends SetSchema | undefined> | SetSchemaAsync | undefined> ? DotPath : TSchema extends LooseTupleSchema | undefined> | LooseTupleSchemaAsync | undefined> | StrictTupleSchema | undefined> | StrictTupleSchemaAsync | undefined> | TupleSchema | undefined> | TupleSchemaAsync | undefined> ? TuplePath : TSchema extends TupleWithRestSchema | undefined> | TupleWithRestSchemaAsync | undefined> ? TuplePath | DotPath : TSchema extends LazySchema | LazySchemaAsync | NonNullableSchema | undefined> | NonNullableSchemaAsync | undefined> | NonNullishSchema | undefined> | NonNullishSchemaAsync | undefined> | NonOptionalSchema | undefined> | NonOptionalSchemaAsync | undefined> | NullableSchema>, null>> | NullableSchemaAsync> | BaseSchemaAsync>, null>> | NullishSchema>, null | undefined>> | NullishSchemaAsync> | BaseSchemaAsync>, null | undefined>> | OptionalSchema>, undefined>> | OptionalSchemaAsync> | BaseSchemaAsync>, undefined>> ? IssueDotPath : never; + +/** + * Config type. + */ +interface Config> { + /** + * The selected language. + */ + readonly lang?: string; + /** + * The error message. + */ + readonly message?: ErrorMessage; + /** + * Whether it was abort early. + */ + readonly abortEarly?: boolean; + /** + * Whether the pipe was abort early. + */ + readonly abortPipeEarly?: boolean; +} + +/** + * Await action async type. + */ +interface AwaitActionAsync> extends BaseTransformationAsync, never> { + /** + * The action type. + */ + readonly type: 'await'; + /** + * The action reference. + */ + readonly reference: typeof awaitAsync; +} +/** + * Creates an await transformation action. + * + * @returns An await action. + */ +declare function awaitAsync>(): AwaitActionAsync; + +/** + * Base64 issue type. + */ +interface Base64Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'base64'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The Base64 regex. + */ + readonly requirement: RegExp; +} +/** + * Base64 action type. + */ +interface Base64Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'base64'; + /** + * The action reference. + */ + readonly reference: typeof base64; + /** + * The expected property. + */ + readonly expects: null; + /** + * The Base64 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [Base64](https://en.wikipedia.org/wiki/Base64) validation action. + * + * @returns A Base64 action. + */ +declare function base64(): Base64Action; +/** + * Creates a [Base64](https://en.wikipedia.org/wiki/Base64) validation action. + * + * @param message The error message. + * + * @returns A Base64 action. + */ +declare function base64> | undefined>(message: TMessage): Base64Action; + +/** + * BIC issue type. + */ +interface BicIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'bic'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The BIC regex. + */ + readonly requirement: RegExp; +} +/** + * BIC action type. + */ +interface BicAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'bic'; + /** + * The action reference. + */ + readonly reference: typeof bic; + /** + * The expected property. + */ + readonly expects: null; + /** + * The BIC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [BIC](https://en.wikipedia.org/wiki/ISO_9362) validation action. + * + * @returns A BIC action. + */ +declare function bic(): BicAction; +/** + * Creates a [BIC](https://en.wikipedia.org/wiki/ISO_9362) validation action. + * + * @param message The error message. + * + * @returns A BIC action. + */ +declare function bic> | undefined>(message: TMessage): BicAction; + +/** + * Brand symbol. + */ +declare const BrandSymbol: unique symbol; +/** + * Brand name type. + */ +type BrandName = string | number | symbol; +/** + * Brand type. + */ +interface Brand { + [BrandSymbol]: { + [TValue in TName]: TValue; + }; +} +/** + * Brand action type. + */ +interface BrandAction extends BaseTransformation, never> { + /** + * The action type. + */ + readonly type: 'brand'; + /** + * The action reference. + */ + readonly reference: typeof brand; + /** + * The brand name. + */ + readonly name: TName; +} +/** + * Creates a brand transformation action. + * + * @param name The brand name. + * + * @returns A brand action. + */ +declare function brand(name: TName): BrandAction; + +/** + * Bytes issue type. + */ +interface BytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'bytes'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required bytes. + */ + readonly requirement: TRequirement; +} +/** + * Bytes action type. + */ +interface BytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'bytes'; + /** + * The action reference. + */ + readonly reference: typeof bytes; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The required bytes. + * + * @returns A bytes action. + */ +declare function bytes(requirement: TRequirement): BytesAction; +/** + * Creates a [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The required bytes. + * @param message The error message. + * + * @returns A bytes action. + */ +declare function bytes> | undefined>(requirement: TRequirement, message: TMessage): BytesAction; + +/** + * Check issue type. + */ +interface CheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'check'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; +} + +/** + * Check action type. + */ +interface CheckAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'check'; + /** + * The action reference. + */ + readonly reference: typeof check; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * + * @returns A check action. + */ +declare function check(requirement: (input: TInput) => boolean): CheckAction; +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A check action. + */ +declare function check> | undefined>(requirement: (input: TInput) => boolean, message: TMessage): CheckAction; + +/** + * Check action async type. + */ +interface CheckActionAsync> | undefined> extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'check'; + /** + * The action reference. + */ + readonly reference: typeof checkAsync; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * + * @returns A check action. + */ +declare function checkAsync(requirement: (input: TInput) => MaybePromise): CheckActionAsync; +/** + * Creates a check validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A check action. + */ +declare function checkAsync> | undefined>(requirement: (input: TInput) => MaybePromise, message: TMessage): CheckActionAsync; + +/** + * Array input type. + */ +type ArrayInput = MaybeReadonly; +/** + * Array requirement type. + */ +type ArrayRequirement = (item: TInput[number], index: number, array: TInput) => boolean; +/** + * Content input type. + */ +type ContentInput = string | MaybeReadonly; +/** + * Content requirement type. + */ +type ContentRequirement = TInput extends readonly unknown[] ? TInput[number] : TInput; +/** + * Length input type. + */ +type LengthInput = string | ArrayLike; +/** + * Size input type. + */ +type SizeInput = Blob | Map | Set; +/** + * Value input type. + */ +type ValueInput = string | number | bigint | boolean | Date; + +/** + * Check items issue type. + */ +interface CheckItemsIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'check_items'; + /** + * The expected input. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Check items action type. + */ +interface CheckItemsAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'check_items'; + /** + * The action reference. + */ + readonly reference: typeof checkItems; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an check items validation action. + * + * @param requirement The validation function. + * + * @returns An check items action. + */ +declare function checkItems(requirement: ArrayRequirement): CheckItemsAction; +/** + * Creates an check items validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns An check items action. + */ +declare function checkItems> | undefined>(requirement: ArrayRequirement, message: TMessage): CheckItemsAction; + +/** + * Credit card issue type. + */ +interface CreditCardIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'credit_card'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * Credit card action type. + */ +interface CreditCardAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'credit_card'; + /** + * The action reference. + */ + readonly reference: typeof creditCard; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [credit card](https://en.wikipedia.org/wiki/Payment_card_number) validation action. + * + * @returns A Credit card action. + */ +declare function creditCard(): CreditCardAction; +/** + * Creates a [credit card](https://en.wikipedia.org/wiki/Payment_card_number) validation action. + * + * @param message The error message. + * + * @returns A credit card action. + */ +declare function creditCard> | undefined>(message: TMessage): CreditCardAction; + +/** + * Cuid2 issue type. + */ +interface Cuid2Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'cuid2'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The Cuid2 regex. + */ + readonly requirement: RegExp; +} +/** + * Cuid2 action type. + */ +interface Cuid2Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'cuid2'; + /** + * The action reference. + */ + readonly reference: typeof cuid2; + /** + * The expected property. + */ + readonly expects: null; + /** + * The Cuid2 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [Cuid2](https://github.com/paralleldrive/cuid2) validation action. + * + * @returns A Cuid2 action. + */ +declare function cuid2(): Cuid2Action; +/** + * Creates a [Cuid2](https://github.com/paralleldrive/cuid2) validation action. + * + * @param message The error message. + * + * @returns A Cuid2 action. + */ +declare function cuid2> | undefined>(message: TMessage): Cuid2Action; + +/** + * Decimal issue type. + */ +interface DecimalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'decimal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The decimal regex. + */ + readonly requirement: RegExp; +} +/** + * Decimal action type. + */ +interface DecimalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'decimal'; + /** + * The action reference. + */ + readonly reference: typeof decimal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The decimal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [decimal](https://en.wikipedia.org/wiki/Decimal) validation action. + * + * @returns An decimal action. + */ +declare function decimal(): DecimalAction; +/** + * Creates a [decimal](https://en.wikipedia.org/wiki/Decimal) validation action. + * + * @param message The error message. + * + * @returns An decimal action. + */ +declare function decimal> | undefined>(message: TMessage): DecimalAction; + +/** + * Description action type. + */ +interface DescriptionAction extends BaseMetadata { + /** + * The action type. + */ + readonly type: 'description'; + /** + * The action reference. + */ + readonly reference: typeof description; + /** + * The description text. + */ + readonly description: TDescription; +} +/** + * Creates a description metadata action. + * + * @param description_ The description text. + * + * @returns A description action. + */ +declare function description(description_: TDescription): DescriptionAction; + +/** + * Email issue type. + */ +interface EmailIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'email'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The email regex. + */ + readonly requirement: RegExp; +} +/** + * Email action type. + */ +interface EmailAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'email'; + /** + * The action reference. + */ + readonly reference: typeof email; + /** + * The expected property. + */ + readonly expects: null; + /** + * The email regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [email](https://en.wikipedia.org/wiki/Email_address) validation + * action. + * + * Hint: This validation action intentionally only validates common email + * addresses. If you are interested in an action that covers the entire + * specification, please see issue [#204](https://github.com/fabian-hiller/valibot/issues/204). + * + * @returns An email action. + */ +declare function email(): EmailAction; +/** + * Creates an [email](https://en.wikipedia.org/wiki/Email_address) validation + * action. + * + * Hint: This validation action intentionally only validates common email + * addresses. If you are interested in an action that covers the entire + * specification, please see issue [#204](https://github.com/fabian-hiller/valibot/issues/204). + * + * @param message The error message. + * + * @returns An email action. + */ +declare function email> | undefined>(message: TMessage): EmailAction; + +/** + * Emoji issue type. + */ +interface EmojiIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'emoji'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The emoji regex. + */ + readonly requirement: RegExp; +} +/** + * Emoji action type. + */ +interface EmojiAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'emoji'; + /** + * The action reference. + */ + readonly reference: typeof emoji; + /** + * The expected property. + */ + readonly expects: null; + /** + * The emoji regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [emoji](https://en.wikipedia.org/wiki/Emoji) validation action. + * + * @returns An emoji action. + */ +declare function emoji(): EmojiAction; +/** + * Creates an [emoji](https://en.wikipedia.org/wiki/Emoji) validation action. + * + * @param message The error message. + * + * @returns An emoji action. + */ +declare function emoji> | undefined>(message: TMessage): EmojiAction; + +/** + * Empty issue type. + */ +interface EmptyIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'empty'; + /** + * The expected input. + */ + readonly expected: '0'; + /** + * The received input. + */ + readonly received: `${number}`; +} +/** + * Empty action type. + */ +interface EmptyAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'empty'; + /** + * The action reference. + */ + readonly reference: typeof empty; + /** + * The expected property. + */ + readonly expects: '0'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an empty validation action. + * + * @returns An empty action. + */ +declare function empty(): EmptyAction; +/** + * Creates an empty validation action. + * + * @param message The error message. + * + * @returns An empty action. + */ +declare function empty> | undefined>(message: TMessage): EmptyAction; + +/** + * Ends with issue type. + */ +interface EndsWithIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ends_with'; + /** + * The expected property. + */ + readonly expected: `"${TRequirement}"`; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The end string. + */ + readonly requirement: TRequirement; +} +/** + * Ends with action type. + */ +interface EndsWithAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ends_with'; + /** + * The action reference. + */ + readonly reference: typeof endsWith; + /** + * The expected property. + */ + readonly expects: `"${TRequirement}"`; + /** + * The end string. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an ends with validation action. + * + * @param requirement The end string. + * + * @returns An ends with action. + */ +declare function endsWith(requirement: TRequirement): EndsWithAction; +/** + * Creates an ends with validation action. + * + * @param requirement The end string. + * @param message The error message. + * + * @returns An ends with action. + */ +declare function endsWith> | undefined>(requirement: TRequirement, message: TMessage): EndsWithAction; + +/** + * Every item issue type. + */ +interface EveryItemIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'every_item'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Every item action type. + */ +interface EveryItemAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'every_item'; + /** + * The action reference. + */ + readonly reference: typeof everyItem; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an every item validation action. + * + * @param requirement The validation function. + * + * @returns An every item action. + */ +declare function everyItem(requirement: ArrayRequirement): EveryItemAction; +/** + * Creates an every item validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns An every item action. + */ +declare function everyItem> | undefined>(requirement: ArrayRequirement, message: TMessage): EveryItemAction; + +/** + * Excludes issue type. + */ +interface ExcludesIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'excludes'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The content to be excluded. + */ + readonly requirement: TRequirement; +} +/** + * Excludes action type. + */ +interface ExcludesAction, TMessage extends ErrorMessage> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'excludes'; + /** + * The action reference. + */ + readonly reference: typeof excludes; + /** + * The expected property. + */ + readonly expects: string; + /** + * The content to be excluded. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an excludes validation action. + * + * @param requirement The content to be excluded. + * + * @returns An excludes action. + */ +declare function excludes>(requirement: TRequirement): ExcludesAction; +/** + * Creates an excludes validation action. + * + * @param requirement The content to be excluded. + * @param message The error message. + * + * @returns An excludes action. + */ +declare function excludes, const TMessage extends ErrorMessage> | undefined>(requirement: TRequirement, message: TMessage): ExcludesAction; + +/** + * Filter items action type. + */ +interface FilterItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'filter_items'; + /** + * The action reference. + */ + readonly reference: typeof filterItems; + /** + * The filter items operation. + */ + readonly operation: ArrayRequirement; +} +/** + * Creates a filter items transformation action. + * + * @param operation The filter items operation. + * + * @returns A filter items action. + */ +declare function filterItems(operation: ArrayRequirement): FilterItemsAction; + +/** + * Find item action type. + */ +interface FindItemAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'find_item'; + /** + * The action reference. + */ + readonly reference: typeof findItem; + /** + * The find item operation. + */ + readonly operation: ArrayRequirement; +} +/** + * Creates a find item transformation action. + * + * @param operation The find item operation. + * + * @returns A find item action. + */ +declare function findItem(operation: ArrayRequirement): FindItemAction; + +/** + * Finite issue type. + */ +interface FiniteIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'finite'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Finite action type. + */ +interface FiniteAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'finite'; + /** + * The action reference. + */ + readonly reference: typeof finite; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [finite](https://en.wikipedia.org/wiki/Finite) validation action. + * + * @returns A finite action. + */ +declare function finite(): FiniteAction; +/** + * Creates a [finite](https://en.wikipedia.org/wiki/Finite) validation action. + * + * @param message The error message. + * + * @returns A finite action. + */ +declare function finite> | undefined>(message: TMessage): FiniteAction; + +/** + * Hash lengths object. + */ +declare const HASH_LENGTHS: { + readonly md4: 32; + readonly md5: 32; + readonly sha1: 40; + readonly sha256: 64; + readonly sha384: 96; + readonly sha512: 128; + readonly ripemd128: 32; + readonly ripemd160: 40; + readonly tiger128: 32; + readonly tiger160: 40; + readonly tiger192: 48; + readonly crc32: 8; + readonly crc32b: 8; + readonly adler32: 8; +}; +/** + * Hash type type. + */ +type HashType = keyof typeof HASH_LENGTHS; +/** + * Hash issue type. + */ +interface HashIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hash'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hash regex. + */ + readonly requirement: RegExp; +} +/** + * Hash action type. + */ +interface HashAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hash'; + /** + * The action reference. + */ + readonly reference: typeof hash; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hash regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hash](https://en.wikipedia.org/wiki/Hash_function) validation action. + * + * @param types The hash types. + * + * @returns A hash action. + */ +declare function hash(types: [HashType, ...HashType[]]): HashAction; +/** + * Creates a [hash](https://en.wikipedia.org/wiki/Hash_function) validation action. + * + * @param types The hash types. + * @param message The error message. + * + * @returns A hash action. + */ +declare function hash> | undefined>(types: [HashType, ...HashType[]], message: TMessage): HashAction; + +/** + * Hexadecimal issue type. + */ +interface HexadecimalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hexadecimal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hexadecimal regex. + */ + readonly requirement: RegExp; +} +/** + * Hexadecimal action type. + */ +interface HexadecimalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hexadecimal'; + /** + * The action reference. + */ + readonly reference: typeof hexadecimal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hexadecimal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) validation action. + * + * @returns A hexadecimal action. + */ +declare function hexadecimal(): HexadecimalAction; +/** + * Creates a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) validation action. + * + * @param message The error message. + * + * @returns A hexadecimal action. + */ +declare function hexadecimal> | undefined>(message: TMessage): HexadecimalAction; + +/** + * Hex color issue type. + */ +interface HexColorIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'hex_color'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The hex color regex. + */ + readonly requirement: RegExp; +} +/** + * Hex color action type. + */ +interface HexColorAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'hex_color'; + /** + * The action reference. + */ + readonly reference: typeof hexColor; + /** + * The expected property. + */ + readonly expects: null; + /** + * The hex color regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) validation action. + * + * @returns A hex color action. + */ +declare function hexColor(): HexColorAction; +/** + * Creates a [hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) validation action. + * + * @param message The error message. + * + * @returns A hex color action. + */ +declare function hexColor> | undefined>(message: TMessage): HexColorAction; + +/** + * IMEI issue type. + */ +interface ImeiIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'imei'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * IMEI action type. + */ +interface ImeiAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'imei'; + /** + * The action reference. + */ + readonly reference: typeof imei; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) validation action. + * + * Formats: + * - AABBBBBBCCCCCCD + * - AA-BBBBBB-CCCCCC-D + * + * @returns An IMEI action. + */ +declare function imei(): ImeiAction; +/** + * Creates an [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) validation action. + * + * Formats: + * - AABBBBBBCCCCCCD + * - AA-BBBBBB-CCCCCC-D + * + * @param message The error message. + * + * @returns An IMEI action. + */ +declare function imei> | undefined>(message: TMessage): ImeiAction; + +/** + * Includes issue type. + */ +interface IncludesIssue> extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'includes'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The content to be included. + */ + readonly requirement: TRequirement; +} +/** + * Includes action type. + */ +interface IncludesAction, TMessage extends ErrorMessage> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'includes'; + /** + * The action reference. + */ + readonly reference: typeof includes; + /** + * The expected property. + */ + readonly expects: string; + /** + * The content to be included. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an includes validation action. + * + * @param requirement The content to be included. + * + * @returns An includes action. + */ +declare function includes>(requirement: TRequirement): IncludesAction; +/** + * Creates an includes validation action. + * + * @param requirement The content to be included. + * @param message The error message. + * + * @returns An includes action. + */ +declare function includes, const TMessage extends ErrorMessage> | undefined>(requirement: TRequirement, message: TMessage): IncludesAction; + +/** + * Integer issue type. + */ +interface IntegerIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'integer'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Integer action type. + */ +interface IntegerAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'integer'; + /** + * The action reference. + */ + readonly reference: typeof integer; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [integer](https://en.wikipedia.org/wiki/Integer) validation action. + * + * @returns An integer action. + */ +declare function integer(): IntegerAction; +/** + * Creates an [integer](https://en.wikipedia.org/wiki/Integer) validation action. + * + * @param message The error message. + * + * @returns An integer action. + */ +declare function integer> | undefined>(message: TMessage): IntegerAction; + +/** + * IP issue type. + */ +interface IpIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ip'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IP regex. + */ + readonly requirement: RegExp; +} +/** + * IP action type. + */ +interface IpAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ip'; + /** + * The action reference. + */ + readonly reference: typeof ip; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IP regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IP address](https://en.wikipedia.org/wiki/IP_address) validation action. + * + * @returns An IP action. + */ +declare function ip(): IpAction; +/** + * Creates an [IP address](https://en.wikipedia.org/wiki/IP_address) validation action. + * + * @param message The error message. + * + * @returns An IP action. + */ +declare function ip> | undefined>(message: TMessage): IpAction; + +/** + * IPv4 issue type. + */ +interface Ipv4Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ipv4'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IPv4 regex. + */ + readonly requirement: RegExp; +} +/** + * IPv4 action type. + */ +interface Ipv4Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ipv4'; + /** + * The action reference. + */ + readonly reference: typeof ipv4; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IPv4 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IPv4](https://en.wikipedia.org/wiki/IPv4) address validation action. + * + * @returns An IPv4 action. + */ +declare function ipv4(): Ipv4Action; +/** + * Creates an [IPv4](https://en.wikipedia.org/wiki/IPv4) address validation action. + * + * @param message The error message. + * + * @returns An IPv4 action. + */ +declare function ipv4> | undefined>(message: TMessage): Ipv4Action; + +/** + * IPv6 issue type. + */ +interface Ipv6Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ipv6'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The IPv6 regex. + */ + readonly requirement: RegExp; +} +/** + * IPv6 action type. + */ +interface Ipv6Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ipv6'; + /** + * The action reference. + */ + readonly reference: typeof ipv6; + /** + * The expected property. + */ + readonly expects: null; + /** + * The IPv6 regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [IPv6](https://en.wikipedia.org/wiki/IPv6) address validation action. + * + * @returns An IPv6 action. + */ +declare function ipv6(): Ipv6Action; +/** + * Creates an [IPv6](https://en.wikipedia.org/wiki/IPv6) address validation action. + * + * @param message The error message. + * + * @returns An IPv6 action. + */ +declare function ipv6> | undefined>(message: TMessage): Ipv6Action; + +/** + * ISO date issue type. + */ +interface IsoDateIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_date'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO date regex. + */ + readonly requirement: RegExp; +} +/** + * ISO date action type. + */ +interface IsoDateAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_date'; + /** + * The action reference. + */ + readonly reference: typeof isoDate; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO date regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO date](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-dd + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31" is valid although June has only + * 30 days. + * + * @returns An ISO date action. + */ +declare function isoDate(): IsoDateAction; +/** + * Creates an [ISO date](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-dd + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31" is valid although June has only + * 30 days. + * + * @param message The error message. + * + * @returns An ISO date action. + */ +declare function isoDate> | undefined>(message: TMessage): IsoDateAction; + +/** + * ISO date time issue type. + */ +interface IsoDateTimeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_date_time'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO date time regex. + */ + readonly requirement: RegExp; +} +/** + * ISO date time action type. + */ +interface IsoDateTimeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_date_time'; + /** + * The action reference. + */ + readonly reference: typeof isoDateTime; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO date time regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO date time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-ddThh:mm + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00" is valid although June has only + * 30 days. + * + * @returns An ISO date time action. + */ +declare function isoDateTime(): IsoDateTimeAction; +/** + * Creates an [ISO date time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-mm-ddThh:mm + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00" is valid although June has only + * 30 days. + * + * @param message The error message. + * + * @returns An ISO date time action. + */ +declare function isoDateTime> | undefined>(message: TMessage): IsoDateTimeAction; + +/** + * ISO time issue type. + */ +interface IsoTimeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_time'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO time regex. + */ + readonly requirement: RegExp; +} +/** + * ISO time action type. + */ +interface IsoTimeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_time'; + /** + * The action reference. + */ + readonly reference: typeof isoTime; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO time regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm + * + * @returns An ISO time action. + */ +declare function isoTime(): IsoTimeAction; +/** + * Creates an [ISO time](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm + * + * @param message The error message. + * + * @returns An ISO time action. + */ +declare function isoTime> | undefined>(message: TMessage): IsoTimeAction; + +/** + * ISO time second issue type. + */ +interface IsoTimeSecondIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_time_second'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO time with seconds regex. + */ + readonly requirement: RegExp; +} +/** + * ISO time second action type. + */ +interface IsoTimeSecondAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_time_second'; + /** + * The action reference. + */ + readonly reference: typeof isoTimeSecond; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO time second regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO time second](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm:ss + * + * @returns An ISO time second action. + */ +declare function isoTimeSecond(): IsoTimeSecondAction; +/** + * Creates an [ISO time second](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: hh:mm:ss + * + * @param message The error message. + * + * @returns An ISO time second action. + */ +declare function isoTimeSecond> | undefined>(message: TMessage): IsoTimeSecondAction; + +/** + * ISO timestamp issue type. + */ +interface IsoTimestampIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_timestamp'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO timestamp regex. + */ + readonly requirement: RegExp; +} +/** + * ISO timestamp action type. + */ +interface IsoTimestampAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_timestamp'; + /** + * The action reference. + */ + readonly reference: typeof isoTimestamp; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO timestamp regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO timestamp](https://en.wikipedia.org/wiki/ISO_8601) validation + * action. + * + * Formats: + * - yyyy-mm-ddThh:mm:ss.sssZ + * - yyyy-mm-ddThh:mm:ss.sss±hh:mm + * - yyyy-mm-ddThh:mm:ss.sss±hhmm + * + * Hint: To support timestamps with lower or higher accuracy, the millisecond + * specification can be removed or contain up to 9 digits. + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00:00.000Z" is valid although + * June has only 30 days. + * + * @returns An ISO timestamp action. + */ +declare function isoTimestamp(): IsoTimestampAction; +/** + * Creates an [ISO timestamp](https://en.wikipedia.org/wiki/ISO_8601) validation + * action. + * + * Formats: + * - yyyy-mm-ddThh:mm:ss.sssZ + * - yyyy-mm-ddThh:mm:ss.sss±hh:mm + * - yyyy-mm-ddThh:mm:ss.sss±hhmm + * - yyyy-mm-ddThh:mm:ss.sss±hh + * + * Hint: To support timestamps with lower or higher accuracy, the millisecond + * specification can be removed or contain up to 9 digits. + * + * Hint: The regex used cannot validate the maximum number of days based on + * year and month. For example, "2023-06-31T00:00:00.000Z" is valid although + * June has only 30 days. + * + * @param message The error message. + * + * @returns An ISO timestamp action. + */ +declare function isoTimestamp> | undefined>(message: TMessage): IsoTimestampAction; + +/** + * ISO week issue type. + */ +interface IsoWeekIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'iso_week'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ISO week regex. + */ + readonly requirement: RegExp; +} +/** + * ISO week action type. + */ +interface IsoWeekAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'iso_week'; + /** + * The action reference. + */ + readonly reference: typeof isoWeek; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ISO week regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ISO week](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-Www + * + * Hint: The regex used cannot validate the maximum number of weeks based on + * the year. For example, "2021W53" is valid although 2021 has only 52 weeks. + * + * @returns An ISO week action. + */ +declare function isoWeek(): IsoWeekAction; +/** + * Creates an [ISO week](https://en.wikipedia.org/wiki/ISO_8601) validation action. + * + * Format: yyyy-Www + * + * Hint: The regex used cannot validate the maximum number of weeks based on + * the year. For example, "2021W53" is valid although 2021 has only 52 weeks. + * + * @param message The error message. + * + * @returns An ISO week action. + */ +declare function isoWeek> | undefined>(message: TMessage): IsoWeekAction; + +/** + * Length issue type. + */ +interface LengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'length'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required length. + */ + readonly requirement: TRequirement; +} +/** + * Length action type. + */ +interface LengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'length'; + /** + * The action reference. + */ + readonly reference: typeof length; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a length validation action. + * + * @param requirement The required length. + * + * @returns A length action. + */ +declare function length(requirement: TRequirement): LengthAction; +/** + * Creates a length validation action. + * + * @param requirement The required length. + * @param message The error message. + * + * @returns A length action. + */ +declare function length> | undefined>(requirement: TRequirement, message: TMessage): LengthAction; + +/** + * MAC issue type. + */ +interface MacIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The MAC regex. + */ + readonly requirement: RegExp; +} +/** + * MAC action type. + */ +interface MacAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac'; + /** + * The action reference. + */ + readonly reference: typeof mac; + /** + * The expected property. + */ + readonly expects: null; + /** + * The MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A MAC action. + */ +declare function mac(): MacAction; +/** + * Creates a [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A MAC action. + */ +declare function mac> | undefined>(message: TMessage): MacAction; + +/** + * 48-bit MAC issue type. + */ +interface Mac48Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac48'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The 48-bit MAC regex. + */ + readonly requirement: RegExp; +} +/** + * 48-bit MAC action type. + */ +interface Mac48Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac48'; + /** + * The action reference. + */ + readonly reference: typeof mac48; + /** + * The expected property. + */ + readonly expects: null; + /** + * The 48-bit MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a 48-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A 48-bit MAC action. + */ +declare function mac48(): Mac48Action; +/** + * Creates a 48-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A 48-bit MAC action. + */ +declare function mac48> | undefined>(message: TMessage): Mac48Action; + +/** + * 64-bit MAC issue type. + */ +interface Mac64Issue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mac64'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The 64-bit MAC regex. + */ + readonly requirement: RegExp; +} +/** + * 64-bit MAC action type. + */ +interface Mac64Action> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mac64'; + /** + * The action reference. + */ + readonly reference: typeof mac64; + /** + * The expected property. + */ + readonly expects: null; + /** + * The 64-bit MAC regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a 64-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @returns A 64-bit MAC action. + */ +declare function mac64(): Mac64Action; +/** + * Creates a 64-bit [MAC address](https://en.wikipedia.org/wiki/MAC_address) validation action. + * + * @param message The error message. + * + * @returns A 64-bit MAC action. + */ +declare function mac64> | undefined>(message: TMessage): Mac64Action; + +/** + * Array action type. + */ +type ArrayAction$2 = (item: TInput[number], index: number, array: TInput) => TOutput; +/** + * Map items action type. + */ +interface MapItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'map_items'; + /** + * The action reference. + */ + readonly reference: typeof mapItems; + /** + * The map items operation. + */ + readonly operation: ArrayAction$2; +} +/** + * Creates a map items transformation action. + * + * @param operation The map items operation. + * + * @returns A map items action. + */ +declare function mapItems(operation: ArrayAction$2): MapItemsAction; + +/** + * Max bytes issue type. + */ +interface MaxBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_bytes'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum bytes. + */ + readonly requirement: TRequirement; +} +/** + * Max bytes action type. + */ +interface MaxBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_bytes'; + /** + * The action reference. + */ + readonly reference: typeof maxBytes; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The maximum bytes. + * + * @returns A max bytes action. + */ +declare function maxBytes(requirement: TRequirement): MaxBytesAction; +/** + * Creates a max [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The maximum bytes. + * @param message The error message. + * + * @returns A max bytes action. + */ +declare function maxBytes> | undefined>(requirement: TRequirement, message: TMessage): MaxBytesAction; + +/** + * Max length issue type. + */ +interface MaxLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_length'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum length. + */ + readonly requirement: TRequirement; +} +/** + * Max length action type. + */ +interface MaxLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_length'; + /** + * The action reference. + */ + readonly reference: typeof maxLength; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max length validation action. + * + * @param requirement The maximum length. + * + * @returns A max length action. + */ +declare function maxLength(requirement: TRequirement): MaxLengthAction; +/** + * Creates a max length validation action. + * + * @param requirement The maximum length. + * @param message The error message. + * + * @returns A max length action. + */ +declare function maxLength> | undefined>(requirement: TRequirement, message: TMessage): MaxLengthAction; + +/** + * Max size issue type. + */ +interface MaxSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_size'; + /** + * The expected property. + */ + readonly expected: `<=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The maximum size. + */ + readonly requirement: TRequirement; +} +/** + * Max size action type. + */ +interface MaxSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_size'; + /** + * The action reference. + */ + readonly reference: typeof maxSize; + /** + * The expected property. + */ + readonly expects: `<=${TRequirement}`; + /** + * The maximum size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max size validation action. + * + * @param requirement The maximum size. + * + * @returns A max size action. + */ +declare function maxSize(requirement: TRequirement): MaxSizeAction; +/** + * Creates a max size validation action. + * + * @param requirement The maximum size. + * @param message The error message. + * + * @returns A max size action. + */ +declare function maxSize> | undefined>(requirement: TRequirement, message: TMessage): MaxSizeAction; + +/** + * Max value issue type. + */ +interface MaxValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'max_value'; + /** + * The expected property. + */ + readonly expected: `<=${string}`; + /** + * The maximum value. + */ + readonly requirement: TRequirement; +} +/** + * Max value action type. + */ +interface MaxValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'max_value'; + /** + * The action reference. + */ + readonly reference: typeof maxValue; + /** + * The expected property. + */ + readonly expects: `<=${string}`; + /** + * The maximum value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a max value validation action. + * + * @param requirement The maximum value. + * + * @returns A max value action. + */ +declare function maxValue(requirement: TRequirement): MaxValueAction; +/** + * Creates a max value validation action. + * + * @param requirement The maximum value. + * @param message The error message. + * + * @returns A max value action. + */ +declare function maxValue> | undefined>(requirement: TRequirement, message: TMessage): MaxValueAction; + +/** + * Requirement type. + */ +type Requirement = readonly `${string}/${string}`[]; +/** + * MIME type issue type. + */ +interface MimeTypeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'mime_type'; + /** + * The expected input. + */ + readonly expected: string; + /** + * The received input. + */ + readonly received: `"${string}"`; + /** + * The MIME types. + */ + readonly requirement: TRequirement; +} +/** + * MIME type action type. + */ +interface MimeTypeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'mime_type'; + /** + * The action reference. + */ + readonly reference: typeof mimeType; + /** + * The expected property. + */ + readonly expects: string; + /** + * The MIME types. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [MIME type](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types) validation action. + * + * @param requirement The MIME types. + * + * @returns A MIME type action. + */ +declare function mimeType(requirement: TRequirement): MimeTypeAction; +/** + * Creates a [MIME type](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types) validation action. + * + * @param requirement The MIME types. + * @param message The error message. + * + * @returns A MIME type action. + */ +declare function mimeType> | undefined>(requirement: TRequirement, message: TMessage): MimeTypeAction; + +/** + * Min bytes issue type. + */ +interface MinBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_bytes'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum bytes. + */ + readonly requirement: TRequirement; +} +/** + * Min bytes action type. + */ +interface MinBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_bytes'; + /** + * The action reference. + */ + readonly reference: typeof minBytes; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The minimum bytes. + * + * @returns A min bytes action. + */ +declare function minBytes(requirement: TRequirement): MinBytesAction; +/** + * Creates a min [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The minimum bytes. + * @param message The error message. + * + * @returns A min bytes action. + */ +declare function minBytes> | undefined>(requirement: TRequirement, message: TMessage): MinBytesAction; + +/** + * Min length issue type. + */ +interface MinLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_length'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum length. + */ + readonly requirement: TRequirement; +} +/** + * Min length action type. + */ +interface MinLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_length'; + /** + * The action reference. + */ + readonly reference: typeof minLength; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min length validation action. + * + * @param requirement The minimum length. + * + * @returns A min length action. + */ +declare function minLength(requirement: TRequirement): MinLengthAction; +/** + * Creates a min length validation action. + * + * @param requirement The minimum length. + * @param message The error message. + * + * @returns A min length action. + */ +declare function minLength> | undefined>(requirement: TRequirement, message: TMessage): MinLengthAction; + +/** + * Min size issue type. + */ +interface MinSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_size'; + /** + * The expected property. + */ + readonly expected: `>=${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The minimum size. + */ + readonly requirement: TRequirement; +} +/** + * Min size action type. + */ +interface MinSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_size'; + /** + * The action reference. + */ + readonly reference: typeof minSize; + /** + * The expected property. + */ + readonly expects: `>=${TRequirement}`; + /** + * The minimum size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min size validation action. + * + * @param requirement The minimum size. + * + * @returns A min size action. + */ +declare function minSize(requirement: TRequirement): MinSizeAction; +/** + * Creates a min size validation action. + * + * @param requirement The minimum size. + * @param message The error message. + * + * @returns A min size action. + */ +declare function minSize> | undefined>(requirement: TRequirement, message: TMessage): MinSizeAction; + +/** + * Min value issue type. + */ +interface MinValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'min_value'; + /** + * The expected property. + */ + readonly expected: `>=${string}`; + /** + * The minimum value. + */ + readonly requirement: TRequirement; +} +/** + * Min value action type. + */ +interface MinValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'min_value'; + /** + * The action reference. + */ + readonly reference: typeof minValue; + /** + * The expected property. + */ + readonly expects: `>=${string}`; + /** + * The minimum value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a min value validation action. + * + * @param requirement The minimum value. + * + * @returns A min value action. + */ +declare function minValue(requirement: TRequirement): MinValueAction; +/** + * Creates a min value validation action. + * + * @param requirement The minimum value. + * @param message The error message. + * + * @returns A min value action. + */ +declare function minValue> | undefined>(requirement: TRequirement, message: TMessage): MinValueAction; + +/** + * Multiple of issue type. + */ +interface MultipleOfIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'multiple_of'; + /** + * The expected property. + */ + readonly expected: `%${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The divisor. + */ + readonly requirement: TRequirement; +} +/** + * Multiple of action type. + */ +interface MultipleOfAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'multiple_of'; + /** + * The action reference. + */ + readonly reference: typeof multipleOf; + /** + * The expected property. + */ + readonly expects: `%${TRequirement}`; + /** + * The divisor. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [multiple](https://en.wikipedia.org/wiki/Multiple_(mathematics)) of validation action. + * + * @param requirement The divisor. + * + * @returns A multiple of action. + */ +declare function multipleOf(requirement: TRequirement): MultipleOfAction; +/** + * Creates a [multiple](https://en.wikipedia.org/wiki/Multiple_(mathematics)) of validation action. + * + * @param requirement The divisor. + * @param message The error message. + * + * @returns A multiple of action. + */ +declare function multipleOf> | undefined>(requirement: TRequirement, message: TMessage): MultipleOfAction; + +/** + * Non empty issue type. + */ +interface NonEmptyIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'non_empty'; + /** + * The expected input. + */ + readonly expected: '!0'; + /** + * The received input. + */ + readonly received: '0'; +} +/** + * Non empty action type. + */ +interface NonEmptyAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'non_empty'; + /** + * The action reference. + */ + readonly reference: typeof nonEmpty; + /** + * The expected property. + */ + readonly expects: '!0'; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a non-empty validation action. + * + * @returns A non-empty action. + */ +declare function nonEmpty(): NonEmptyAction; +/** + * Creates a non-empty validation action. + * + * @param message The error message. + * + * @returns A non-empty action. + */ +declare function nonEmpty> | undefined>(message: TMessage): NonEmptyAction; + +/** + * Normalize form type. + */ +type NormalizeForm = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'; +/** + * Normalize action type. + */ +interface NormalizeAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'normalize'; + /** + * The action reference. + */ + readonly reference: typeof normalize; + /** + * The normalization form. + */ + readonly form: TForm; +} +/** + * Creates a normalize transformation action. + * + * @returns A normalize action. + */ +declare function normalize(): NormalizeAction; +/** + * Creates a normalize transformation action. + * + * @param form The normalization form. + * + * @returns A normalize action. + */ +declare function normalize(form: TForm): NormalizeAction; + +/** + * Not bytes issue type. + */ +interface NotBytesIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_bytes'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The not required bytes. + */ + readonly requirement: TRequirement; +} +/** + * Not bytes action type. + */ +interface NotBytesAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_bytes'; + /** + * The action reference. + */ + readonly reference: typeof notBytes; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required bytes. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The not required bytes. + * + * @returns A not bytes action. + */ +declare function notBytes(requirement: TRequirement): NotBytesAction; +/** + * Creates a not [bytes](https://en.wikipedia.org/wiki/Byte) validation action. + * + * @param requirement The not required bytes. + * @param message The error message. + * + * @returns A not bytes action. + */ +declare function notBytes> | undefined>(requirement: TRequirement, message: TMessage): NotBytesAction; + +/** + * Not length issue type. + */ +interface NotLengthIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_length'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${TRequirement}`; + /** + * The not required length. + */ + readonly requirement: TRequirement; +} +/** + * Not length action type. + */ +interface NotLengthAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_length'; + /** + * The action reference. + */ + readonly reference: typeof notLength; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required length. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not length validation action. + * + * @param requirement The not required length. + * + * @returns A not length action. + */ +declare function notLength(requirement: TRequirement): NotLengthAction; +/** + * Creates a not length validation action. + * + * @param requirement The not required length. + * @param message The error message. + * + * @returns A not length action. + */ +declare function notLength> | undefined>(requirement: TRequirement, message: TMessage): NotLengthAction; + +/** + * Not size issue type. + */ +interface NotSizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_size'; + /** + * The expected property. + */ + readonly expected: `!${TRequirement}`; + /** + * The received property. + */ + readonly received: `${TRequirement}`; + /** + * The not required size. + */ + readonly requirement: TRequirement; +} +/** + * Not size action type. + */ +interface NotSizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_size'; + /** + * The action reference. + */ + readonly reference: typeof notSize; + /** + * The expected property. + */ + readonly expects: `!${TRequirement}`; + /** + * The not required size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not size validation action. + * + * @param requirement The not required size. + * + * @returns A not size action. + */ +declare function notSize(requirement: TRequirement): NotSizeAction; +/** + * Creates a not size validation action. + * + * @param requirement The not required size. + * @param message The error message. + * + * @returns A not size action. + */ +declare function notSize> | undefined>(requirement: TRequirement, message: TMessage): NotSizeAction; + +/** + * Not value issue type. + */ +interface NotValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'not_value'; + /** + * The expected property. + */ + readonly expected: `!${string}`; + /** + * The not required value. + */ + readonly requirement: TRequirement; +} +/** + * Not value action type. + */ +interface NotValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'not_value'; + /** + * The action reference. + */ + readonly reference: typeof notValue; + /** + * The expected property. + */ + readonly expects: `!${string}`; + /** + * The not required value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a not value validation action. + * + * @param requirement The not required value. + * + * @returns A not value action. + */ +declare function notValue(requirement: TRequirement): NotValueAction; +/** + * Creates a not value validation action. + * + * @param requirement The not required value. + * @param message The error message. + * + * @returns A not value action. + */ +declare function notValue> | undefined>(requirement: TRequirement, message: TMessage): NotValueAction; + +/** + * Octal issue type. + */ +interface OctalIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'octal'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The octal regex. + */ + readonly requirement: RegExp; +} +/** + * Octal action type. + */ +interface OctalAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'octal'; + /** + * The action reference. + */ + readonly reference: typeof octal; + /** + * The expected property. + */ + readonly expects: null; + /** + * The octal regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [octal](https://en.wikipedia.org/wiki/Octal) validation action. + * + * @returns An octal action. + */ +declare function octal(): OctalAction; +/** + * Creates an [octal](https://en.wikipedia.org/wiki/Octal) validation action. + * + * @param message The error message. + * + * @returns An octal action. + */ +declare function octal> | undefined>(message: TMessage): OctalAction; + +/** + * Partial input type. + */ +type PartialInput = Record | ArrayLike; +/** + * Partial check issue type. + */ +interface PartialCheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'partial_check'; + /** + * The expected input. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: (input: TInput) => MaybePromise; +} + +/** + * Partial check action type. + */ +interface PartialCheckAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'partial_check'; + /** + * The action reference. + */ + readonly reference: typeof partialCheck; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TSelection) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * + * @returns A partial check action. + */ +declare function partialCheck[], const TSelection extends DeepPickN>(pathList: TPathList, requirement: (input: TSelection) => boolean): PartialCheckAction; +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * @param message The error message. + * + * @returns A partial check action. + */ +declare function partialCheck[], const TSelection extends DeepPickN, const TMessage extends ErrorMessage> | undefined>(pathList: TPathList, requirement: (input: TSelection) => boolean, message: TMessage): PartialCheckAction; + +/** + * Partial check action async type. + */ +interface PartialCheckActionAsync> | undefined> extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'partial_check'; + /** + * The action reference. + */ + readonly reference: typeof partialCheckAsync; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: TSelection) => MaybePromise; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * + * @returns A partial check action. + */ +declare function partialCheckAsync[], const TSelection extends DeepPickN>(pathList: TPathList, requirement: (input: TSelection) => MaybePromise): PartialCheckActionAsync; +/** + * Creates a partial check validation action. + * + * @param pathList The selected paths. + * @param requirement The validation function. + * @param message The error message. + * + * @returns A partial check action. + */ +declare function partialCheckAsync[], const TSelection extends DeepPickN, const TMessage extends ErrorMessage> | undefined>(pathList: TPathList, requirement: (input: TSelection) => MaybePromise, message: TMessage): PartialCheckActionAsync; + +/** + * Raw check issue type. + */ +interface RawCheckIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'raw_check'; +} +/** + * Issue info type. + */ +interface IssueInfo$1 { + label?: string; + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; +} +/** + * Add issue type. + */ +type AddIssue$1 = (info?: IssueInfo$1) => void; +/** + * Context type. + */ +interface Context$2 { + readonly dataset: Dataset>; + readonly config: Config>; + readonly addIssue: AddIssue$1; +} + +/** + * Raw check action type. + */ +interface RawCheckAction extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'raw_check'; + /** + * The action reference. + */ + readonly reference: typeof rawCheck; + /** + * The expected property. + */ + readonly expects: null; +} +/** + * Creates a raw check validation action. + * + * @param action The validation action. + * + * @returns A raw check action. + */ +declare function rawCheck(action: (context: Context$2) => void): RawCheckAction; + +/** + * Raw check action async type. + */ +interface RawCheckActionAsync extends BaseValidationAsync> { + /** + * The action type. + */ + readonly type: 'raw_check'; + /** + * The action reference. + */ + readonly reference: typeof rawCheckAsync; + /** + * The expected property. + */ + readonly expects: null; +} +/** + * Creates a raw check validation action. + * + * @param action The validation action. + * + * @returns A raw check action. + */ +declare function rawCheckAsync(action: (context: Context$2) => MaybePromise): RawCheckActionAsync; + +/** + * Raw transform issue type. + */ +interface RawTransformIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'transformation'; + /** + * The issue type. + */ + readonly type: 'raw_transform'; +} +/** + * Issue info type. + */ +interface IssueInfo { + label?: string; + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; +} +/** + * Add issue type. + */ +type AddIssue = (info?: IssueInfo) => void; +/** + * Context type. + */ +interface Context$1 { + readonly dataset: TypedDataset; + readonly config: Config>; + readonly addIssue: AddIssue; + readonly NEVER: never; +} + +/** + * Raw transform action type. + */ +interface RawTransformAction extends BaseTransformation> { + /** + * The action type. + */ + readonly type: 'raw_transform'; + /** + * The action reference. + */ + readonly reference: typeof rawTransform; +} +/** + * Creates a raw transformation action. + * + * @param action The transformation action. + * + * @returns A raw transform action. + */ +declare function rawTransform(action: (context: Context$1) => TOutput): RawTransformAction; + +/** + * Raw transform action async type. + */ +interface RawTransformActionAsync extends BaseTransformationAsync> { + /** + * The action type. + */ + readonly type: 'raw_transform'; + /** + * The action reference. + */ + readonly reference: typeof rawTransformAsync; +} +/** + * Creates a raw transformation action. + * + * @param action The transformation action. + * + * @returns A raw transform action. + */ +declare function rawTransformAsync(action: (context: Context$1) => MaybePromise): RawTransformActionAsync; + +/** + * Readonly action type. + */ +interface ReadonlyAction extends BaseTransformation, never> { + /** + * The action type. + */ + readonly type: 'readonly'; + /** + * The action reference. + */ + readonly reference: typeof readonly; +} +/** + * Creates a readonly transformation action. + * + * @returns A readonly action. + */ +declare function readonly(): ReadonlyAction; + +/** + * Array action type. + */ +type ArrayAction$1 = (output: TOutput, item: TInput[number], index: number, array: TInput) => TOutput; +/** + * Reduce items action type. + */ +interface ReduceItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'reduce_items'; + /** + * The action reference. + */ + readonly reference: typeof reduceItems; + /** + * The reduce items operation. + */ + readonly operation: ArrayAction$1; + /** + * The initial value. + */ + readonly initial: TOutput; +} +/** + * Creates a reduce items transformation action. + * + * @param operation The reduce items operation. + * @param initial The initial value. + * + * @returns A reduce items action. + */ +declare function reduceItems(operation: ArrayAction$1, initial: TOutput): ReduceItemsAction; + +/** + * Regex issue type. + */ +interface RegexIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'regex'; + /** + * The expected input. + */ + readonly expected: string; + /** + * The received input. + */ + readonly received: `"${string}"`; + /** + * The regex pattern. + */ + readonly requirement: RegExp; +} +/** + * Regex action type. + */ +interface RegexAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'regex'; + /** + * The action reference. + */ + readonly reference: typeof regex; + /** + * The expected property. + */ + readonly expects: string; + /** + * The regex pattern. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a [regex](https://en.wikipedia.org/wiki/Regular_expression) validation action. + * + * @param requirement The regex pattern. + * + * @returns A regex action. + */ +declare function regex(requirement: RegExp): RegexAction; +/** + * Creates a [regex](https://en.wikipedia.org/wiki/Regular_expression) validation action. + * + * @param requirement The regex pattern. + * @param message The error message. + * + * @returns A regex action. + */ +declare function regex> | undefined>(requirement: RegExp, message: TMessage): RegexAction; + +/** + * Safe integer issue type. + */ +interface SafeIntegerIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'safe_integer'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; +} +/** + * Safe integer action type. + */ +interface SafeIntegerAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'safe_integer'; + /** + * The action reference. + */ + readonly reference: typeof safeInteger; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: number) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a safe integer validation action. + * + * @returns A safe integer action. + */ +declare function safeInteger(): SafeIntegerAction; +/** + * Creates a safe integer validation action. + * + * @param message The error message. + * + * @returns A safe integer action. + */ +declare function safeInteger> | undefined>(message: TMessage): SafeIntegerAction; + +/** + * Size issue type. + */ +interface SizeIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'size'; + /** + * The expected property. + */ + readonly expected: `${TRequirement}`; + /** + * The received property. + */ + readonly received: `${number}`; + /** + * The required size. + */ + readonly requirement: TRequirement; +} +/** + * Size action type. + */ +interface SizeAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'size'; + /** + * The action reference. + */ + readonly reference: typeof size; + /** + * The expected property. + */ + readonly expects: `${TRequirement}`; + /** + * The required size. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a size validation action. + * + * @param requirement The required size. + * + * @returns A size action. + */ +declare function size(requirement: TRequirement): SizeAction; +/** + * Creates a size validation action. + * + * @param requirement The required size. + * @param message The error message. + * + * @returns A size action. + */ +declare function size> | undefined>(requirement: TRequirement, message: TMessage): SizeAction; + +/** + * Some item issue type. + */ +interface SomeItemIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'some_item'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; +} +/** + * Some item action type. + */ +interface SomeItemAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'some_item'; + /** + * The action reference. + */ + readonly reference: typeof someItem; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: ArrayRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a some item validation action. + * + * @param requirement The validation function. + * + * @returns A some item action. + */ +declare function someItem(requirement: ArrayRequirement): SomeItemAction; +/** + * Creates a some item validation action. + * + * @param requirement The validation function. + * @param message The error message. + * + * @returns A some item action. + */ +declare function someItem> | undefined>(requirement: ArrayRequirement, message: TMessage): SomeItemAction; + +/** + * Array action type. + */ +type ArrayAction = (itemA: TInput[number], itemB: TInput[number]) => number; +/** + * Sort items action type. + */ +interface SortItemsAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'sort_items'; + /** + * The action reference. + */ + readonly reference: typeof sortItems; + /** + * The sort items operation. + */ + readonly operation: ArrayAction | undefined; +} +/** + * Creates a sort items transformation action. + * + * @param operation The sort items operation. + * + * @returns A sort items action. + */ +declare function sortItems(operation?: ArrayAction): SortItemsAction; + +/** + * Starts with issue type. + */ +interface StartsWithIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'starts_with'; + /** + * The expected property. + */ + readonly expected: `"${TRequirement}"`; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The start string. + */ + readonly requirement: TRequirement; +} +/** + * Starts with action type. + */ +interface StartsWithAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'starts_with'; + /** + * The action reference. + */ + readonly reference: typeof startsWith; + /** + * The expected property. + */ + readonly expects: `"${TRequirement}"`; + /** + * The start string. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a starts with validation action. + * + * @param requirement The start string. + * + * @returns A starts with action. + */ +declare function startsWith(requirement: TRequirement): StartsWithAction; +/** + * Creates a starts with validation action. + * + * @param requirement The start string. + * @param message The error message. + * + * @returns A starts with action. + */ +declare function startsWith> | undefined>(requirement: TRequirement, message: TMessage): StartsWithAction; + +/** + * To lower case action type. + */ +interface ToLowerCaseAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_lower_case'; + /** + * The action reference. + */ + readonly reference: typeof toLowerCase; +} +/** + * Creates a to lower case transformation action. + * + * @returns A to lower case action. + */ +declare function toLowerCase(): ToLowerCaseAction; + +/** + * To max value action type. + */ +interface ToMaxValueAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_max_value'; + /** + * The action reference. + */ + readonly reference: typeof toMaxValue; + /** + * The maximum value. + */ + readonly requirement: TRequirement; +} +/** + * Creates a to max value transformation action. + * + * @param requirement The maximum value. + * + * @returns A to max value action. + */ +declare function toMaxValue(requirement: TRequirement): ToMaxValueAction; + +/** + * To min value action type. + */ +interface ToMinValueAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_min_value'; + /** + * The action reference. + */ + readonly reference: typeof toMinValue; + /** + * The minimum value. + */ + readonly requirement: TRequirement; +} +/** + * Creates a to min value transformation action. + * + * @param requirement The minimum value. + * + * @returns A to min value action. + */ +declare function toMinValue(requirement: TRequirement): ToMinValueAction; + +/** + * To upper case action type. + */ +interface ToUpperCaseAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'to_upper_case'; + /** + * The action reference. + */ + readonly reference: typeof toUpperCase; +} +/** + * Creates a to upper case transformation action. + * + * @returns A to upper case action. + */ +declare function toUpperCase(): ToUpperCaseAction; + +/** + * Transform action type. + */ +interface TransformAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'transform'; + /** + * The action reference. + */ + readonly reference: typeof transform; + /** + * The transformation operation. + */ + readonly operation: (input: TInput) => TOutput; +} +/** + * Creates a custom transformation action. + * + * @param operation The transformation operation. + * + * @returns A transform action. + */ +declare function transform(operation: (input: TInput) => TOutput): TransformAction; + +/** + * Transform action async type. + */ +interface TransformActionAsync extends BaseTransformationAsync { + /** + * The action type. + */ + readonly type: 'transform'; + /** + * The action reference. + */ + readonly reference: typeof transformAsync; + /** + * The transformation operation. + */ + readonly operation: (input: TInput) => Promise; +} +/** + * Creates a custom transformation action. + * + * @param operation The transformation operation. + * + * @returns A transform action. + */ +declare function transformAsync(operation: (input: TInput) => Promise): TransformActionAsync; + +/** + * Trim action type. + */ +interface TrimAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim'; + /** + * The action reference. + */ + readonly reference: typeof trim; +} +/** + * Creates a trim transformation action. + * + * @returns A trim action. + */ +declare function trim(): TrimAction; + +/** + * Trim end action type. + */ +interface TrimEndAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim_end'; + /** + * The action reference. + */ + readonly reference: typeof trimEnd; +} +/** + * Creates a trim end transformation action. + * + * @returns A trim end action. + */ +declare function trimEnd(): TrimEndAction; + +/** + * Trim start action type. + */ +interface TrimStartAction extends BaseTransformation { + /** + * The action type. + */ + readonly type: 'trim_start'; + /** + * The action reference. + */ + readonly reference: typeof trimStart; +} +/** + * Creates a trim start transformation action. + * + * @returns A trim start action. + */ +declare function trimStart(): TrimStartAction; + +/** + * ULID issue type. + */ +interface UlidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'ulid'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The ULID regex. + */ + readonly requirement: RegExp; +} +/** + * ULID action type. + */ +interface UlidAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'ulid'; + /** + * The action reference. + */ + readonly reference: typeof ulid; + /** + * The expected property. + */ + readonly expects: null; + /** + * The ULID regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [ULID](https://github.com/ulid/spec) validation action. + * + * @returns An ULID action. + */ +declare function ulid(): UlidAction; +/** + * Creates an [ULID](https://github.com/ulid/spec) validation action. + * + * @param message The error message. + * + * @returns An ULID action. + */ +declare function ulid> | undefined>(message: TMessage): UlidAction; + +/** + * URL issue type. + */ +interface UrlIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'url'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; +} +/** + * URL action type. + */ +interface UrlAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'url'; + /** + * The action reference. + */ + readonly reference: typeof url; + /** + * The expected property. + */ + readonly expects: null; + /** + * The validation function. + */ + readonly requirement: (input: string) => boolean; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [URL](https://en.wikipedia.org/wiki/URL) validation action. + * + * Hint: The value is passed to the URL constructor to check if it is valid. + * This check is not perfect. For example, values like "abc:1234" are accepted. + * + * @returns An URL action. + */ +declare function url(): UrlAction; +/** + * Creates an [URL](https://en.wikipedia.org/wiki/URL) validation action. + * + * Hint: The value is passed to the URL constructor to check if it is valid. + * This check is not perfect. For example, values like "abc:1234" are accepted. + * + * @param message The error message. + * + * @returns An URL action. + */ +declare function url> | undefined>(message: TMessage): UrlAction; + +/** + * UUID issue type. + */ +interface UuidIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'uuid'; + /** + * The expected property. + */ + readonly expected: null; + /** + * The received property. + */ + readonly received: `"${string}"`; + /** + * The UUID regex. + */ + readonly requirement: RegExp; +} +/** + * UUID action type. + */ +interface UuidAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'uuid'; + /** + * The action reference. + */ + readonly reference: typeof uuid; + /** + * The expected property. + */ + readonly expects: null; + /** + * The UUID regex. + */ + readonly requirement: RegExp; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates an [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) validation action. + * + * @returns An UUID action. + */ +declare function uuid(): UuidAction; +/** + * Creates an [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) validation action. + * + * @param message The error message. + * + * @returns An UUID action. + */ +declare function uuid> | undefined>(message: TMessage): UuidAction; + +/** + * Value issue type. + */ +interface ValueIssue extends BaseIssue { + /** + * The issue kind. + */ + readonly kind: 'validation'; + /** + * The issue type. + */ + readonly type: 'value'; + /** + * The expected property. + */ + readonly expected: string; + /** + * The required value. + */ + readonly requirement: TRequirement; +} +/** + * Value action type. + */ +interface ValueAction> | undefined> extends BaseValidation> { + /** + * The action type. + */ + readonly type: 'value'; + /** + * The action reference. + */ + readonly reference: typeof value; + /** + * The expected property. + */ + readonly expects: string; + /** + * The required value. + */ + readonly requirement: TRequirement; + /** + * The error message. + */ + readonly message: TMessage; +} +/** + * Creates a value validation action. + * + * @param requirement The required value. + * + * @returns A value action. + */ +declare function value(requirement: TRequirement): ValueAction; +/** + * Creates a value validation action. + * + * @param requirement The required value. + * @param message The error message. + * + * @returns A value action. + */ +declare function value> | undefined>(requirement: TRequirement, message: TMessage): ValueAction; + +/** + * [Base64](https://en.wikipedia.org/wiki/Base64) regex. + */ +declare const BASE64_REGEX: RegExp; +/** + * [BIC](https://en.wikipedia.org/wiki/ISO_9362) regex. + */ +declare const BIC_REGEX: RegExp; +/** + * [Cuid2](https://github.com/paralleldrive/cuid2) regex. + */ +declare const CUID2_REGEX: RegExp; +/** + * [Decimal](https://en.wikipedia.org/wiki/Decimal) regex. + */ +declare const DECIMAL_REGEX: RegExp; +/** + * Email regex. + */ +declare const EMAIL_REGEX: RegExp; +/** + * Emoji regex from [emoji-regex-xs](https://github.com/slevithan/emoji-regex-xs) v1.0.0 (MIT license). + * + * Hint: We decided against the newer `/^\p{RGI_Emoji}+$/v` regex because it is + * not supported in older runtimes and does not match all emoji. + */ +declare const EMOJI_REGEX: RegExp; +/** + * [Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) regex. + */ +declare const HEXADECIMAL_REGEX: RegExp; +/** + * [Hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) regex. + */ +declare const HEX_COLOR_REGEX: RegExp; +/** + * [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) regex. + */ +declare const IMEI_REGEX: RegExp; +/** + * [IPv4](https://en.wikipedia.org/wiki/IPv4) regex. + */ +declare const IPV4_REGEX: RegExp; +/** + * [IPv6](https://en.wikipedia.org/wiki/IPv6) regex. + */ +declare const IPV6_REGEX: RegExp; +/** + * [IP](https://en.wikipedia.org/wiki/IP_address) regex. + */ +declare const IP_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date regex. + */ +declare const ISO_DATE_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time regex. + */ +declare const ISO_DATE_TIME_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time regex. + */ +declare const ISO_TIME_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time with seconds regex. + */ +declare const ISO_TIME_SECOND_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp regex. + */ +declare const ISO_TIMESTAMP_REGEX: RegExp; +/** + * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) week regex. + */ +declare const ISO_WEEK_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) 48 bit regex. + */ +declare const MAC48_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) 64 bit regex. + */ +declare const MAC64_REGEX: RegExp; +/** + * [MAC](https://en.wikipedia.org/wiki/MAC_address) regex. + */ +declare const MAC_REGEX: RegExp; +/** + * [Octal](https://en.wikipedia.org/wiki/Octal) regex. + */ +declare const OCTAL_REGEX: RegExp; +/** + * [ULID](https://github.com/ulid/spec) regex. + */ +declare const ULID_REGEX: RegExp; +/** + * [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) regex. + */ +declare const UUID_REGEX: RegExp; + +/** + * The global config type. + */ +type GlobalConfig = Omit, 'message'>; +/** + * Sets the global configuration. + * + * @param config The configuration. + */ +declare function setGlobalConfig(config: GlobalConfig): void; +/** + * Returns the global configuration. + * + * @param config The config to merge. + * + * @returns The configuration. + */ +declare function getGlobalConfig>(config?: Config): Config; +/** + * Deletes the global configuration. + */ +declare function deleteGlobalConfig(): void; + +/** + * Sets a global error message. + * + * @param message The error message. + * @param lang The language of the message. + */ +declare function setGlobalMessage(message: ErrorMessage>, lang?: string): void; +/** + * Returns a global error message. + * + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getGlobalMessage(lang?: string): ErrorMessage> | undefined; +/** + * Deletes a global error message. + * + * @param lang The language of the message. + */ +declare function deleteGlobalMessage(lang?: string): void; + +/** + * Sets a schema error message. + * + * @param message The error message. + * @param lang The language of the message. + */ +declare function setSchemaMessage(message: ErrorMessage>, lang?: string): void; +/** + * Returns a schema error message. + * + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getSchemaMessage(lang?: string): ErrorMessage> | undefined; +/** + * Deletes a schema error message. + * + * @param lang The language of the message. + */ +declare function deleteSchemaMessage(lang?: string): void; + +/** + * Reference type. + */ +type Reference = (...args: any[]) => BaseSchema> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync>; +/** + * Sets a specific error message. + * + * @param reference The identifier reference. + * @param message The error message. + * @param lang The language of the message. + */ +declare function setSpecificMessage(reference: TReference, message: ErrorMessage>>, lang?: string): void; +/** + * Returns a specific error message. + * + * @param reference The identifier reference. + * @param lang The language of the message. + * + * @returns The error message. + */ +declare function getSpecificMessage(reference: TReference, lang?: string): ErrorMessage>> | undefined; +/** + * Deletes a specific error message. + * + * @param reference The identifier reference. + * @param lang The language of the message. + */ +declare function deleteSpecificMessage(reference: Reference, lang?: string): void; + +/** + * Context type. + */ +type Context = BaseSchema> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync>; +/** + * Other type. + */ +interface Other { + input?: unknown; + expected?: string; + received?: string; + message?: ErrorMessage>; + path?: [IssuePathItem, ...IssuePathItem[]]; + issues?: [ + BaseIssue>, + ...BaseIssue>[] + ]; +} +/** + * Adds an issue to the dataset. + * + * @param context The issue context. + * @param label The issue label. + * @param dataset The input dataset. + * @param config The configuration. + * @param other The optional props. + * + * @internal + */ +declare function _addIssue(context: TContext, label: string, dataset: Dataset>, config: Config>, other?: Other): void; + +/** + * Checks whether a string with numbers corresponds to the luhn algorithm. + * + * @param input The input to be checked. + * + * @returns Whether input is valid. + * + * @internal + */ +declare function _isLuhnAlgo(input: string): boolean; + +/** + * Disallows inherited object properties and prevents object prototype + * pollution by disallowing certain keys. + * + * @param object The object to check. + * @param key The key to check. + * + * @returns Whether the key is allowed. + * + * @internal + */ +declare function _isValidObjectKey(object: object, key: string): boolean; + +/** + * Joins multiple `expects` values with the given separator. + * + * @param values The `expects` values. + * @param separator The separator. + * + * @returns The joined `expects` property. + * + * @internal + */ +declare function _joinExpects(values: string[], separator: '&' | '|'): string; + +/** + * Stringifies an unknown input to a literal or type string. + * + * @param input The unknown input. + * + * @returns A literal or type string. + * + * @internal + */ +declare function _stringify(input: unknown): string; + +/** + * Creates an object entries definition from a list of keys and a schema. + * + * @param list A list of keys. + * @param schema The schema of the keys. + * + * @returns The object entries. + */ +declare function entriesFromList> | BaseSchemaAsync>>(list: TList, schema: TSchema): Record; + +/** + * Creates and returns the dot path of an issue if possible. + * + * @param issue The issue to get the dot path from. + * + * @returns The dot path or null. + */ +declare function getDotPath(issue: BaseIssue): string | null; +/** + * Creates and returns the dot path of an issue if possible. + * + * @param issue The issue to get the dot path from. + * + * @returns The dot path or null. + */ +declare function getDotPath> | BaseSchemaAsync>>(issue: InferIssue): IssueDotPath | null; + +/** + * A generic type guard to check the kind of an object. + * + * @param kind The kind to check for. + * @param object The object to check. + * + * @returns Whether it matches. + */ +declare function isOfKind(kind: TKind, object: TObject): object is Extract; + +/** + * A generic type guard to check the type of an object. + * + * @param type The type to check for. + * @param object The object to check. + * + * @returns Whether it matches. + */ +declare function isOfType(type: TType, object: TObject): object is Extract; + +/** + * A type guard to check if an error is a ValiError. + * + * @param error The error to check. + * + * @returns Whether its a ValiError. + */ +declare function isValiError> | BaseSchemaAsync>>(error: unknown): error is ValiError; + +/** + * A Valibot error with useful information. + */ +declare class ValiError> | BaseSchemaAsync>> extends Error { + /** + * The error issues. + */ + readonly issues: [InferIssue, ...InferIssue[]]; + /** + * Creates a Valibot error with useful information. + * + * @param issues The error issues. + */ + constructor(issues: [InferIssue, ...InferIssue[]]); +} + +export { type AnySchema, type ArrayInput, type ArrayIssue, type ArrayPathItem, type ArrayRequirement, type ArraySchema, type ArraySchemaAsync, type AwaitActionAsync, BASE64_REGEX, BIC_REGEX, type Base64Action, type Base64Issue, type BaseIssue, type BaseMetadata, type BaseSchema, type BaseSchemaAsync, type BaseTransformation, type BaseTransformationAsync, type BaseValidation, type BaseValidationAsync, type BicAction, type BicIssue, type BigintIssue, type BigintSchema, type BlobIssue, type BlobSchema, type BooleanIssue, type BooleanSchema, type Brand, type BrandAction, type BrandName, BrandSymbol, type BytesAction, type BytesIssue, CUID2_REGEX, type CheckAction, type CheckActionAsync, type CheckIssue, type CheckItemsAction, type CheckItemsIssue, type Class, type Config, type ContentInput, type ContentRequirement, type CreditCardAction, type CreditCardIssue, type Cuid2Action, type Cuid2Issue, type CustomIssue, type CustomSchema, type CustomSchemaAsync, DECIMAL_REGEX, type Dataset, type DateIssue, type DateSchema, type DecimalAction, type DecimalIssue, type DeepPickN, type Default, type DefaultAsync, type DefaultValue, type DescriptionAction, EMAIL_REGEX, EMOJI_REGEX, type EmailAction, type EmailIssue, type EmojiAction, type EmojiIssue, type EmptyAction, type EmptyIssue, type EndsWithAction, type EndsWithIssue, type Enum, type EnumIssue, type EnumSchema, type ErrorMessage, type EveryItemAction, type EveryItemIssue, type ExcludesAction, type ExcludesIssue, type Fallback, type FallbackAsync, type FileIssue, type FileSchema, type FilterItemsAction, type FindItemAction, type FiniteAction, type FiniteIssue, type FirstTupleItem, type FlatErrors, type FunctionIssue, type FunctionSchema, type GenericIssue, type GenericMetadata, type GenericSchema, type GenericSchemaAsync, type GenericTransformation, type GenericTransformationAsync, type GenericValidation, type GenericValidationAsync, type GlobalConfig, HEXADECIMAL_REGEX, HEX_COLOR_REGEX, type HashAction, type HashIssue, type HashType, type HexColorAction, type HexColorIssue, type HexadecimalAction, type HexadecimalIssue, IMEI_REGEX, IPV4_REGEX, IPV6_REGEX, IP_REGEX, ISO_DATE_REGEX, ISO_DATE_TIME_REGEX, ISO_TIMESTAMP_REGEX, ISO_TIME_REGEX, ISO_TIME_SECOND_REGEX, ISO_WEEK_REGEX, type ImeiAction, type ImeiIssue, type IncludesAction, type IncludesIssue, type InferDefault, type InferDefaults, type InferFallback, type InferFallbacks, type InferInput, type InferIntersectInput, type InferIntersectOutput, type InferIssue, type InferMapInput, type InferMapOutput, type InferNonNullableInput, type InferNonNullableIssue, type InferNonNullableOutput, type InferNonNullishInput, type InferNonNullishIssue, type InferNonNullishOutput, type InferNonOptionalInput, type InferNonOptionalIssue, type InferNonOptionalOutput, type InferNullableOutput, type InferNullishOutput, type InferObjectInput, type InferObjectIssue, type InferObjectOutput, type InferOptionalOutput, type InferOutput, type InferRecordInput, type InferRecordOutput, type InferSetInput, type InferSetOutput, type InferTupleInput, type InferTupleIssue, type InferTupleOutput, type InferVariantIssue, type InstanceIssue, type InstanceSchema, type IntegerAction, type IntegerIssue, type IntersectIssue, type IntersectOptions, type IntersectOptionsAsync, type IntersectSchema, type IntersectSchemaAsync, type IpAction, type IpIssue, type Ipv4Action, type Ipv4Issue, type Ipv6Action, type Ipv6Issue, type IsoDateAction, type IsoDateIssue, type IsoDateTimeAction, type IsoDateTimeIssue, type IsoTimeAction, type IsoTimeIssue, type IsoTimeSecondAction, type IsoTimeSecondIssue, type IsoTimestampAction, type IsoTimestampIssue, type IsoWeekAction, type IsoWeekIssue, type IssueDotPath, type IssuePathItem, type LastTupleItem, type LazySchema, type LazySchemaAsync, type LengthAction, type LengthInput, type LengthIssue, type Literal, type LiteralIssue, type LiteralSchema, type LooseObjectIssue, type LooseObjectSchema, type LooseObjectSchemaAsync, type LooseTupleIssue, type LooseTupleSchema, type LooseTupleSchemaAsync, MAC48_REGEX, MAC64_REGEX, MAC_REGEX, type Mac48Action, type Mac48Issue, type Mac64Action, type Mac64Issue, type MacAction, type MacIssue, type MapIssue, type MapItemsAction, type MapPathItem, type MapSchema, type MapSchemaAsync, type MarkOptional, type MaxBytesAction, type MaxBytesIssue, type MaxLengthAction, type MaxLengthIssue, type MaxSizeAction, type MaxSizeIssue, type MaxValueAction, type MaxValueIssue, type MaybePromise, type MaybeReadonly, type MimeTypeAction, type MimeTypeIssue, type MinBytesAction, type MinBytesIssue, type MinLengthAction, type MinLengthIssue, type MinSizeAction, type MinSizeIssue, type MinValueAction, type MinValueIssue, type MultipleOfAction, type MultipleOfIssue, type NanIssue, type NanSchema, type NeverIssue, type NeverSchema, type NoPipe, type NonEmptyAction, type NonEmptyIssue, type NonNullable$1 as NonNullable, type NonNullableIssue, type NonNullableSchema, type NonNullableSchemaAsync, type NonNullish, type NonNullishIssue, type NonNullishSchema, type NonNullishSchemaAsync, type NonOptional, type NonOptionalIssue, type NonOptionalSchema, type NonOptionalSchemaAsync, type NormalizeAction, type NormalizeForm, type NotBytesAction, type NotBytesIssue, type NotLengthAction, type NotLengthIssue, type NotSizeAction, type NotSizeIssue, type NotValueAction, type NotValueIssue, type NullIssue, type NullSchema, type NullableSchema, type NullableSchemaAsync, type NullishSchema, type NullishSchemaAsync, type NumberIssue, type NumberSchema, OCTAL_REGEX, type ObjectEntries, type ObjectEntriesAsync, type ObjectIssue, type ObjectKeys, type ObjectPathItem, type ObjectSchema, type ObjectSchemaAsync, type ObjectWithRestIssue, type ObjectWithRestSchema, type ObjectWithRestSchemaAsync, type OctalAction, type OctalIssue, type OptionalSchema, type OptionalSchemaAsync, type Parser, type ParserAsync, type PartialCheckAction, type PartialCheckActionAsync, type PartialCheckIssue, type PathKeys, type PicklistIssue, type PicklistOptions, type PicklistSchema, type PipeAction, type PipeActionAsync, type PipeItem, type PipeItemAsync, type Prettify, type PromiseIssue, type PromiseSchema, type RawCheckAction, type RawCheckActionAsync, type RawCheckIssue, type RawTransformAction, type RawTransformActionAsync, type RawTransformIssue, type ReadonlyAction, type RecordIssue, type RecordSchema, type RecordSchemaAsync, type ReduceItemsAction, type RegexAction, type RegexIssue, type SafeIntegerAction, type SafeIntegerIssue, type SafeParseResult, type SafeParser, type SafeParserAsync, type SchemaWithFallback, type SchemaWithFallbackAsync, type SchemaWithOmit, type SchemaWithPartial, type SchemaWithPartialAsync, type SchemaWithPick, type SchemaWithPipe, type SchemaWithPipeAsync, type SchemaWithRequired, type SchemaWithRequiredAsync, type SetIssue, type SetPathItem, type SetSchema, type SetSchemaAsync, type SizeAction, type SizeInput, type SizeIssue, type SomeItemAction, type SomeItemIssue, type SortItemsAction, type StartsWithAction, type StartsWithIssue, type StrictObjectIssue, type StrictObjectSchema, type StrictObjectSchemaAsync, type StrictTupleIssue, type StrictTupleSchema, type StrictTupleSchemaAsync, type StringIssue, type StringSchema, type SymbolIssue, type SymbolSchema, type ToLowerCaseAction, type ToMaxValueAction, type ToMinValueAction, type ToUpperCaseAction, type TransformAction, type TransformActionAsync, type TrimAction, type TrimEndAction, type TrimStartAction, type TupleIssue, type TupleItems, type TupleItemsAsync, type TupleSchema, type TupleSchemaAsync, type TupleWithRestIssue, type TupleWithRestSchema, type TupleWithRestSchemaAsync, type TypedDataset, ULID_REGEX, UUID_REGEX, type UlidAction, type UlidIssue, type UndefinedIssue, type UndefinedSchema, type UnionIssue, type UnionOptions, type UnionOptionsAsync, type UnionSchema, type UnionSchemaAsync, type UnionToIntersect, type UnionToTuple, type UnknownPathItem, type UnknownSchema, type UntypedDataset, type UrlAction, type UrlIssue, type UuidAction, type UuidIssue, ValiError, type ValueAction, type ValueInput, type ValueIssue, type VariantIssue, type VariantOptions, type VariantOptionsAsync, type VariantSchema, type VariantSchemaAsync, type VoidIssue, type VoidSchema, _addIssue, _isLuhnAlgo, _isValidObjectKey, _joinExpects, _stringify, any, array, arrayAsync, awaitAsync, base64, bic, bigint, blob, boolean, brand, bytes, check, checkAsync, checkItems, config, creditCard, cuid2, custom, customAsync, date, decimal, deleteGlobalConfig, deleteGlobalMessage, deleteSchemaMessage, deleteSpecificMessage, description, email, emoji, empty, endsWith, entriesFromList, enum_ as enum, enum_, everyItem, excludes, fallback, fallbackAsync, file, filterItems, findItem, finite, flatten, forward, forwardAsync, function_ as function, function_, getDefault, getDefaults, getDefaultsAsync, getDotPath, getFallback, getFallbacks, getFallbacksAsync, getGlobalConfig, getGlobalMessage, getSchemaMessage, getSpecificMessage, hash, hexColor, hexadecimal, imei, includes, instance, integer, intersect, intersectAsync, ip, ipv4, ipv6, is, isOfKind, isOfType, isValiError, isoDate, isoDateTime, isoTime, isoTimeSecond, isoTimestamp, isoWeek, keyof, lazy, lazyAsync, length, literal, looseObject, looseObjectAsync, looseTuple, looseTupleAsync, mac, mac48, mac64, map, mapAsync, mapItems, maxBytes, maxLength, maxSize, maxValue, mimeType, minBytes, minLength, minSize, minValue, multipleOf, nan, never, nonEmpty, nonNullable, nonNullableAsync, nonNullish, nonNullishAsync, nonOptional, nonOptionalAsync, normalize, notBytes, notLength, notSize, notValue, null_ as null, null_, nullable, nullableAsync, nullish, nullishAsync, number, object, objectAsync, objectWithRest, objectWithRestAsync, octal, omit, optional, optionalAsync, parse, parseAsync, parser, parserAsync, partial, partialAsync, partialCheck, partialCheckAsync, pick, picklist, pipe, pipeAsync, promise, rawCheck, rawCheckAsync, rawTransform, rawTransformAsync, readonly, record, recordAsync, reduceItems, regex, required, requiredAsync, safeInteger, safeParse, safeParseAsync, safeParser, safeParserAsync, set, setAsync, setGlobalConfig, setGlobalMessage, setSchemaMessage, setSpecificMessage, size, someItem, sortItems, startsWith, strictObject, strictObjectAsync, strictTuple, strictTupleAsync, string, symbol, toLowerCase, toMaxValue, toMinValue, toUpperCase, transform, transformAsync, trim, trimEnd, trimStart, tuple, tupleAsync, tupleWithRest, tupleWithRestAsync, ulid, undefined_ as undefined, undefined_, union, unionAsync, unknown, unwrap, url, uuid, value, variant, variantAsync, void_ as void, void_ }; diff --git a/src/libMPC/node_modules/valibot/dist/index.js b/src/libMPC/node_modules/valibot/dist/index.js new file mode 100644 index 0000000..4cc683b --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.js @@ -0,0 +1,5697 @@ +// src/actions/await/awaitAsync.ts +function awaitAsync() { + return { + kind: "transformation", + type: "await", + reference: awaitAsync, + async: true, + async _run(dataset) { + dataset.value = await dataset.value; + return dataset; + } + }; +} + +// src/regex.ts +var BASE64_REGEX = /^(?:[\da-z+/]{4})*(?:[\da-z+/]{2}==|[\da-z+/]{3}=)?$/iu; +var BIC_REGEX = /^[A-Z]{6}(?!00)[\dA-Z]{2}(?:[\dA-Z]{3})?$/u; +var CUID2_REGEX = /^[a-z][\da-z]*$/u; +var DECIMAL_REGEX = /^\d+$/u; +var EMAIL_REGEX = /^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu; +var EMOJI_REGEX = ( + // eslint-disable-next-line redos-detector/no-unsafe-regex, regexp/no-dupe-disjunctions -- false positives + /^(?:[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}))*)+$/u +); +var HEXADECIMAL_REGEX = /^(?:0[hx])?[\da-f]+$/iu; +var HEX_COLOR_REGEX = /^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/iu; +var IMEI_REGEX = /^\d{15}$|^\d{2}-\d{6}-\d{6}-\d$/u; +var IPV4_REGEX = ( + // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive + /^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$/u +); +var IPV6_REGEX = /^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu; +var IP_REGEX = /^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$|^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu; +var ISO_DATE_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])$/u; +var ISO_DATE_TIME_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])T(?:0\d|1\d|2[0-3]):[0-5]\d$/u; +var ISO_TIME_REGEX = /^(?:0\d|1\d|2[0-3]):[0-5]\d$/u; +var ISO_TIME_SECOND_REGEX = /^(?:0\d|1\d|2[0-3])(?::[0-5]\d){2}$/u; +var ISO_TIMESTAMP_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])T(?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z|[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u; +var ISO_WEEK_REGEX = /^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/u; +var MAC48_REGEX = /^(?:[\da-f]{2}:){5}[\da-f]{2}$|^(?:[\da-f]{2}-){5}[\da-f]{2}$|^(?:[\da-f]{4}\.){2}[\da-f]{4}$/iu; +var MAC64_REGEX = /^(?:[\da-f]{2}:){7}[\da-f]{2}$|^(?:[\da-f]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu; +var MAC_REGEX = /^(?:[\da-f]{2}:){5}[\da-f]{2}$|^(?:[\da-f]{2}-){5}[\da-f]{2}$|^(?:[\da-f]{4}\.){2}[\da-f]{4}$|^(?:[\da-f]{2}:){7}[\da-f]{2}$|^(?:[\da-f]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu; +var OCTAL_REGEX = /^(?:0o)?[0-7]+$/iu; +var ULID_REGEX = /^[\da-hjkmnp-tv-z]{26}$/iu; +var UUID_REGEX = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu; + +// src/storages/globalConfig/globalConfig.ts +var store; +function setGlobalConfig(config2) { + store = { ...store, ...config2 }; +} +function getGlobalConfig(config2) { + return { + lang: config2?.lang ?? store?.lang, + message: config2?.message, + abortEarly: config2?.abortEarly ?? store?.abortEarly, + abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly + }; +} +function deleteGlobalConfig() { + store = void 0; +} + +// src/storages/globalMessage/globalMessage.ts +var store2; +function setGlobalMessage(message, lang) { + if (!store2) store2 = /* @__PURE__ */ new Map(); + store2.set(lang, message); +} +function getGlobalMessage(lang) { + return store2?.get(lang); +} +function deleteGlobalMessage(lang) { + store2?.delete(lang); +} + +// src/storages/schemaMessage/schemaMessage.ts +var store3; +function setSchemaMessage(message, lang) { + if (!store3) store3 = /* @__PURE__ */ new Map(); + store3.set(lang, message); +} +function getSchemaMessage(lang) { + return store3?.get(lang); +} +function deleteSchemaMessage(lang) { + store3?.delete(lang); +} + +// src/storages/specificMessage/specificMessage.ts +var store4; +function setSpecificMessage(reference, message, lang) { + if (!store4) store4 = /* @__PURE__ */ new Map(); + if (!store4.get(reference)) store4.set(reference, /* @__PURE__ */ new Map()); + store4.get(reference).set(lang, message); +} +function getSpecificMessage(reference, lang) { + return store4?.get(reference)?.get(lang); +} +function deleteSpecificMessage(reference, lang) { + store4?.get(reference)?.delete(lang); +} + +// src/utils/_stringify/_stringify.ts +function _stringify(input) { + const type = typeof input; + if (type === "string") { + return `"${input}"`; + } + if (type === "number" || type === "bigint" || type === "boolean") { + return `${input}`; + } + if (type === "object" || type === "function") { + return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null"; + } + return type; +} + +// src/utils/_addIssue/_addIssue.ts +function _addIssue(context, label, dataset, config2, other) { + const input = other && "input" in other ? other.input : dataset.value; + const expected = other?.expected ?? context.expects ?? null; + const received = other?.received ?? _stringify(input); + const issue = { + kind: context.kind, + type: context.type, + input, + expected, + received, + message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`, + // @ts-expect-error + requirement: context.requirement, + path: other?.path, + issues: other?.issues, + lang: config2.lang, + abortEarly: config2.abortEarly, + abortPipeEarly: config2.abortPipeEarly + }; + const isSchema = context.kind === "schema"; + const message = other?.message ?? // @ts-expect-error + context.message ?? getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? getSchemaMessage(issue.lang) : null) ?? config2.message ?? getGlobalMessage(issue.lang); + if (message) { + issue.message = typeof message === "function" ? message(issue) : message; + } + if (isSchema) { + dataset.typed = false; + } + if (dataset.issues) { + dataset.issues.push(issue); + } else { + dataset.issues = [issue]; + } +} + +// src/utils/_isLuhnAlgo/_isLuhnAlgo.ts +var NON_DIGIT_REGEX = /\D/gu; +function _isLuhnAlgo(input) { + const number2 = input.replace(NON_DIGIT_REGEX, ""); + let length2 = number2.length; + let bit = 1; + let sum = 0; + while (length2) { + const value2 = +number2[--length2]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value2] : value2; + } + return sum % 10 === 0; +} + +// src/utils/_isValidObjectKey/_isValidObjectKey.ts +function _isValidObjectKey(object2, key) { + return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor"; +} + +// src/utils/_joinExpects/_joinExpects.ts +function _joinExpects(values, separator) { + const list = [...new Set(values)]; + if (list.length > 1) { + return `(${list.join(` ${separator} `)})`; + } + return list[0] ?? "never"; +} + +// src/utils/entriesFromList/entriesFromList.ts +function entriesFromList(list, schema) { + const entries = {}; + for (const key of list) { + entries[key] = schema; + } + return entries; +} + +// src/utils/getDotPath/getDotPath.ts +function getDotPath(issue) { + if (issue.path) { + let key = ""; + for (const item of issue.path) { + if (typeof item.key === "string" || typeof item.key === "number") { + if (key) { + key += `.${item.key}`; + } else { + key += item.key; + } + } else { + return null; + } + } + return key; + } + return null; +} + +// src/utils/isOfKind/isOfKind.ts +function isOfKind(kind, object2) { + return object2.kind === kind; +} + +// src/utils/isOfType/isOfType.ts +function isOfType(type, object2) { + return object2.type === type; +} + +// src/utils/isValiError/isValiError.ts +function isValiError(error) { + return error instanceof ValiError; +} + +// src/utils/ValiError/ValiError.ts +var ValiError = class extends Error { + /** + * The error issues. + */ + issues; + /** + * Creates a Valibot error with useful information. + * + * @param issues The error issues. + */ + constructor(issues) { + super(issues[0].message); + this.name = "ValiError"; + this.issues = issues; + } +}; + +// src/actions/base64/base64.ts +function base64(message) { + return { + kind: "validation", + type: "base64", + reference: base64, + async: false, + expects: null, + requirement: BASE64_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "Base64", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/bic/bic.ts +function bic(message) { + return { + kind: "validation", + type: "bic", + reference: bic, + async: false, + expects: null, + requirement: BIC_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "BIC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/brand/brand.ts +function brand(name) { + return { + kind: "transformation", + type: "brand", + reference: brand, + async: false, + name, + _run(dataset) { + return dataset; + } + }; +} + +// src/actions/bytes/bytes.ts +function bytes(requirement, message) { + return { + kind: "validation", + type: "bytes", + reference: bytes, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 !== this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/check/check.ts +function check(requirement, message) { + return { + kind: "validation", + type: "check", + reference: check, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/check/checkAsync.ts +function checkAsync(requirement, message) { + return { + kind: "validation", + type: "check", + reference: checkAsync, + async: true, + expects: null, + requirement, + message, + async _run(dataset, config2) { + if (dataset.typed && !await this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/checkItems/checkItems.ts +function checkItems(requirement, message) { + return { + kind: "validation", + type: "check_items", + reference: checkItems, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + for (let index = 0; index < dataset.value.length; index++) { + const item = dataset.value[index]; + if (!this.requirement(item, index, dataset.value)) { + _addIssue(this, "item", dataset, config2, { + input: item, + path: [ + { + type: "array", + origin: "value", + input: dataset.value, + key: index, + value: item + } + ] + }); + } + } + } + return dataset; + } + }; +} + +// src/actions/creditCard/creditCard.ts +var CREDIT_CARD_REGEX = /^(?:\d{14,19}|\d{4}(?: \d{3,6}){2,4}|\d{4}(?:-\d{3,6}){2,4})$/u; +var SANITIZE_REGEX = /[- ]/gu; +var PROVIDER_REGEX_LIST = [ + // American Express + /^3[47]\d{13}$/u, + // Diners Club + /^3(?:0[0-5]|[68]\d)\d{11,13}$/u, + // Discover + /^6(?:011|5\d{2})\d{12,15}$/u, + // JCB + /^(?:2131|1800|35\d{3})\d{11}$/u, + // Mastercard + /^5[1-5]\d{2}|(?:222\d|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}$/u, + // UnionPay + /^(?:6[27]\d{14,17}|81\d{14,17})$/u, + // Visa + /^4\d{12}(?:\d{3,6})?$/u +]; +function creditCard(message) { + return { + kind: "validation", + type: "credit_card", + reference: creditCard, + async: false, + expects: null, + requirement(input) { + let sanitized; + return CREDIT_CARD_REGEX.test(input) && // Remove any hyphens and blanks + (sanitized = input.replace(SANITIZE_REGEX, "")) && // Check if it matches a provider + PROVIDER_REGEX_LIST.some((regex2) => regex2.test(sanitized)) && // Check if passes luhn algorithm + _isLuhnAlgo(sanitized); + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "credit card", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/cuid2/cuid2.ts +function cuid2(message) { + return { + kind: "validation", + type: "cuid2", + reference: cuid2, + async: false, + expects: null, + requirement: CUID2_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "Cuid2", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/decimal/decimal.ts +function decimal(message) { + return { + kind: "validation", + type: "decimal", + reference: decimal, + async: false, + expects: null, + requirement: DECIMAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "decimal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/description/description.ts +function description(description_) { + return { + kind: "metadata", + type: "description", + reference: description, + description: description_ + }; +} + +// src/actions/email/email.ts +function email(message) { + return { + kind: "validation", + type: "email", + reference: email, + expects: null, + async: false, + requirement: EMAIL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "email", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/emoji/emoji.ts +function emoji(message) { + return { + kind: "validation", + type: "emoji", + reference: emoji, + async: false, + expects: null, + requirement: EMOJI_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "emoji", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/empty/empty.ts +function empty(message) { + return { + kind: "validation", + type: "empty", + reference: empty, + async: false, + expects: "0", + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length > 0) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/endsWith/endsWith.ts +function endsWith(requirement, message) { + return { + kind: "validation", + type: "ends_with", + reference: endsWith, + async: false, + expects: `"${requirement}"`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.endsWith(this.requirement)) { + _addIssue(this, "end", dataset, config2, { + received: `"${dataset.value.slice(-this.requirement.length)}"` + }); + } + return dataset; + } + }; +} + +// src/actions/everyItem/everyItem.ts +function everyItem(requirement, message) { + return { + kind: "validation", + type: "every_item", + reference: everyItem, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.every(this.requirement)) { + _addIssue(this, "item", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/excludes/excludes.ts +function excludes(requirement, message) { + const received = _stringify(requirement); + return { + kind: "validation", + type: "excludes", + reference: excludes, + async: false, + expects: `!${received}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.includes(this.requirement)) { + _addIssue(this, "content", dataset, config2, { received }); + } + return dataset; + } + }; +} + +// src/actions/filterItems/filterItems.ts +function filterItems(operation) { + return { + kind: "transformation", + type: "filter_items", + reference: filterItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.filter(this.operation); + return dataset; + } + }; +} + +// src/actions/findItem/findItem.ts +function findItem(operation) { + return { + kind: "transformation", + type: "find_item", + reference: findItem, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.find(this.operation); + return dataset; + } + }; +} + +// src/actions/finite/finite.ts +function finite(message) { + return { + kind: "validation", + type: "finite", + reference: finite, + async: false, + expects: null, + requirement: Number.isFinite, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "finite", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hash/hash.ts +var HASH_LENGTHS = { + md4: 32, + md5: 32, + sha1: 40, + sha256: 64, + sha384: 96, + sha512: 128, + ripemd128: 32, + ripemd160: 40, + tiger128: 32, + tiger160: 40, + tiger192: 48, + crc32: 8, + crc32b: 8, + adler32: 8 +}; +function hash(types, message) { + return { + kind: "validation", + type: "hash", + reference: hash, + expects: null, + async: false, + requirement: RegExp( + types.map((type) => `^[a-f0-9]{${HASH_LENGTHS[type]}}$`).join("|"), + "iu" + ), + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hash", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hexadecimal/hexadecimal.ts +function hexadecimal(message) { + return { + kind: "validation", + type: "hexadecimal", + reference: hexadecimal, + async: false, + expects: null, + requirement: HEXADECIMAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hexadecimal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/hexColor/hexColor.ts +function hexColor(message) { + return { + kind: "validation", + type: "hex_color", + reference: hexColor, + async: false, + expects: null, + requirement: HEX_COLOR_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "hex color", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/imei/imei.ts +function imei(message) { + return { + kind: "validation", + type: "imei", + reference: imei, + async: false, + expects: null, + requirement(input) { + return IMEI_REGEX.test(input) && _isLuhnAlgo(input); + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "IMEI", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/includes/includes.ts +function includes(requirement, message) { + const expects = _stringify(requirement); + return { + kind: "validation", + type: "includes", + reference: includes, + async: false, + expects, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.includes(this.requirement)) { + _addIssue(this, "content", dataset, config2, { + received: `!${expects}` + }); + } + return dataset; + } + }; +} + +// src/actions/integer/integer.ts +function integer(message) { + return { + kind: "validation", + type: "integer", + reference: integer, + async: false, + expects: null, + requirement: Number.isInteger, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "integer", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ip/ip.ts +function ip(message) { + return { + kind: "validation", + type: "ip", + reference: ip, + async: false, + expects: null, + requirement: IP_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IP", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ipv4/ipv4.ts +function ipv4(message) { + return { + kind: "validation", + type: "ipv4", + reference: ipv4, + async: false, + expects: null, + requirement: IPV4_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IPv4", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/ipv6/ipv6.ts +function ipv6(message) { + return { + kind: "validation", + type: "ipv6", + reference: ipv6, + async: false, + expects: null, + requirement: IPV6_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "IPv6", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoDate/isoDate.ts +function isoDate(message) { + return { + kind: "validation", + type: "iso_date", + reference: isoDate, + async: false, + expects: null, + requirement: ISO_DATE_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "date", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoDateTime/isoDateTime.ts +function isoDateTime(message) { + return { + kind: "validation", + type: "iso_date_time", + reference: isoDateTime, + async: false, + expects: null, + requirement: ISO_DATE_TIME_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "date-time", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTime/isoTime.ts +function isoTime(message) { + return { + kind: "validation", + type: "iso_time", + reference: isoTime, + async: false, + expects: null, + requirement: ISO_TIME_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "time", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTimeSecond/isoTimeSecond.ts +function isoTimeSecond(message) { + return { + kind: "validation", + type: "iso_time_second", + reference: isoTimeSecond, + async: false, + expects: null, + requirement: ISO_TIME_SECOND_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "time-second", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoTimestamp/isoTimestamp.ts +function isoTimestamp(message) { + return { + kind: "validation", + type: "iso_timestamp", + reference: isoTimestamp, + async: false, + expects: null, + requirement: ISO_TIMESTAMP_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "timestamp", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/isoWeek/isoWeek.ts +function isoWeek(message) { + return { + kind: "validation", + type: "iso_week", + reference: isoWeek, + async: false, + expects: null, + requirement: ISO_WEEK_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "week", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/length/length.ts +function length(requirement, message) { + return { + kind: "validation", + type: "length", + reference: length, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length !== this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/mac/mac.ts +function mac(message) { + return { + kind: "validation", + type: "mac", + reference: mac, + async: false, + expects: null, + requirement: MAC_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mac48/mac48.ts +function mac48(message) { + return { + kind: "validation", + type: "mac48", + reference: mac48, + async: false, + expects: null, + requirement: MAC48_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "48-bit MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mac64/mac64.ts +function mac64(message) { + return { + kind: "validation", + type: "mac64", + reference: mac64, + async: false, + expects: null, + requirement: MAC64_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "64-bit MAC", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/mapItems/mapItems.ts +function mapItems(operation) { + return { + kind: "transformation", + type: "map_items", + reference: mapItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.map(this.operation); + return dataset; + } + }; +} + +// src/actions/maxBytes/maxBytes.ts +function maxBytes(requirement, message) { + return { + kind: "validation", + type: "max_bytes", + reference: maxBytes, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 > this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/maxLength/maxLength.ts +function maxLength(requirement, message) { + return { + kind: "validation", + type: "max_length", + reference: maxLength, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length > this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/maxSize/maxSize.ts +function maxSize(requirement, message) { + return { + kind: "validation", + type: "max_size", + reference: maxSize, + async: false, + expects: `<=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size > this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/maxValue/maxValue.ts +function maxValue(requirement, message) { + return { + kind: "validation", + type: "max_value", + reference: maxValue, + async: false, + expects: `<=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value > this.requirement) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/mimeType/mimeType.ts +function mimeType(requirement, message) { + return { + kind: "validation", + type: "mime_type", + reference: mimeType, + async: false, + expects: _joinExpects( + requirement.map((option) => `"${option}"`), + "|" + ), + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.includes(dataset.value.type)) { + _addIssue(this, "MIME type", dataset, config2, { + received: `"${dataset.value.type}"` + }); + } + return dataset; + } + }; +} + +// src/actions/minBytes/minBytes.ts +function minBytes(requirement, message) { + return { + kind: "validation", + type: "min_bytes", + reference: minBytes, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 < this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/minLength/minLength.ts +function minLength(requirement, message) { + return { + kind: "validation", + type: "min_length", + reference: minLength, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length < this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/minSize/minSize.ts +function minSize(requirement, message) { + return { + kind: "validation", + type: "min_size", + reference: minSize, + async: false, + expects: `>=${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size < this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/minValue/minValue.ts +function minValue(requirement, message) { + return { + kind: "validation", + type: "min_value", + reference: minValue, + async: false, + expects: `>=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value < this.requirement) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/multipleOf/multipleOf.ts +function multipleOf(requirement, message) { + return { + kind: "validation", + type: "multiple_of", + reference: multipleOf, + async: false, + expects: `%${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value % this.requirement !== 0) { + _addIssue(this, "multiple", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/nonEmpty/nonEmpty.ts +function nonEmpty(message) { + return { + kind: "validation", + type: "non_empty", + reference: nonEmpty, + async: false, + expects: "!0", + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length === 0) { + _addIssue(this, "length", dataset, config2, { + received: "0" + }); + } + return dataset; + } + }; +} + +// src/actions/normalize/normalize.ts +function normalize(form) { + return { + kind: "transformation", + type: "normalize", + reference: normalize, + async: false, + form, + _run(dataset) { + dataset.value = dataset.value.normalize(this.form); + return dataset; + } + }; +} + +// src/actions/notBytes/notBytes.ts +function notBytes(requirement, message) { + return { + kind: "validation", + type: "not_bytes", + reference: notBytes, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed) { + const length2 = new TextEncoder().encode(dataset.value).length; + if (length2 === this.requirement) { + _addIssue(this, "bytes", dataset, config2, { + received: `${length2}` + }); + } + } + return dataset; + } + }; +} + +// src/actions/notLength/notLength.ts +function notLength(requirement, message) { + return { + kind: "validation", + type: "not_length", + reference: notLength, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.length === this.requirement) { + _addIssue(this, "length", dataset, config2, { + received: `${dataset.value.length}` + }); + } + return dataset; + } + }; +} + +// src/actions/notSize/notSize.ts +function notSize(requirement, message) { + return { + kind: "validation", + type: "not_size", + reference: notSize, + async: false, + expects: `!${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size === this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/notValue/notValue.ts +function notValue(requirement, message) { + return { + kind: "validation", + type: "not_value", + reference: notValue, + async: false, + expects: requirement instanceof Date ? `!${requirement.toJSON()}` : `!${_stringify(requirement)}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && this.requirement <= dataset.value && this.requirement >= dataset.value) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/actions/octal/octal.ts +function octal(message) { + return { + kind: "validation", + type: "octal", + reference: octal, + async: false, + expects: null, + requirement: OCTAL_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "octal", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/partialCheck/utils/_isPartiallyTyped/_isPartiallyTyped.ts +function _isPartiallyTyped(dataset, pathList) { + if (dataset.issues) { + for (const path of pathList) { + for (const issue of dataset.issues) { + let typed = false; + const bound = Math.min(path.length, issue.path?.length ?? 0); + for (let index = 0; index < bound; index++) { + if (path[index] !== issue.path[index].key) { + typed = true; + break; + } + } + if (!typed) { + return false; + } + } + } + } + return true; +} + +// src/actions/partialCheck/partialCheck.ts +function partialCheck(pathList, requirement, message) { + return { + kind: "validation", + type: "partial_check", + reference: partialCheck, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (_isPartiallyTyped(dataset, pathList) && // @ts-expect-error + !this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/partialCheck/partialCheckAsync.ts +function partialCheckAsync(pathList, requirement, message) { + return { + kind: "validation", + type: "partial_check", + reference: partialCheckAsync, + async: true, + expects: null, + requirement, + message, + async _run(dataset, config2) { + if (_isPartiallyTyped(dataset, pathList) && // @ts-expect-error + !await this.requirement(dataset.value)) { + _addIssue(this, "input", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/rawCheck/rawCheck.ts +function rawCheck(action) { + return { + kind: "validation", + type: "raw_check", + reference: rawCheck, + async: false, + expects: null, + _run(dataset, config2) { + action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info) + }); + return dataset; + } + }; +} + +// src/actions/rawCheck/rawCheckAsync.ts +function rawCheckAsync(action) { + return { + kind: "validation", + type: "raw_check", + reference: rawCheckAsync, + async: true, + expects: null, + async _run(dataset, config2) { + await action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info) + }); + return dataset; + } + }; +} + +// src/actions/rawTransform/rawTransform.ts +function rawTransform(action) { + return { + kind: "transformation", + type: "raw_transform", + reference: rawTransform, + async: false, + _run(dataset, config2) { + const output = action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info), + NEVER: null + }); + if (dataset.issues) { + dataset.typed = false; + } else { + dataset.value = output; + } + return dataset; + } + }; +} + +// src/actions/rawTransform/rawTransformAsync.ts +function rawTransformAsync(action) { + return { + kind: "transformation", + type: "raw_transform", + reference: rawTransformAsync, + async: true, + async _run(dataset, config2) { + const output = await action({ + dataset, + config: config2, + addIssue: (info) => _addIssue(this, info?.label ?? "input", dataset, config2, info), + NEVER: null + }); + if (dataset.issues) { + dataset.typed = false; + } else { + dataset.value = output; + } + return dataset; + } + }; +} + +// src/actions/readonly/readonly.ts +function readonly() { + return { + kind: "transformation", + type: "readonly", + reference: readonly, + async: false, + _run(dataset) { + return dataset; + } + }; +} + +// src/actions/reduceItems/reduceItems.ts +function reduceItems(operation, initial) { + return { + kind: "transformation", + type: "reduce_items", + reference: reduceItems, + async: false, + operation, + initial, + _run(dataset) { + dataset.value = dataset.value.reduce(this.operation, this.initial); + return dataset; + } + }; +} + +// src/actions/regex/regex.ts +function regex(requirement, message) { + return { + kind: "validation", + type: "regex", + reference: regex, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "format", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/safeInteger/safeInteger.ts +function safeInteger(message) { + return { + kind: "validation", + type: "safe_integer", + reference: safeInteger, + async: false, + expects: null, + requirement: Number.isSafeInteger, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "safe integer", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/size/size.ts +function size(requirement, message) { + return { + kind: "validation", + type: "size", + reference: size, + async: false, + expects: `${requirement}`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && dataset.value.size !== this.requirement) { + _addIssue(this, "size", dataset, config2, { + received: `${dataset.value.size}` + }); + } + return dataset; + } + }; +} + +// src/actions/someItem/someItem.ts +function someItem(requirement, message) { + return { + kind: "validation", + type: "some_item", + reference: someItem, + async: false, + expects: null, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.some(this.requirement)) { + _addIssue(this, "item", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/sortItems/sortItems.ts +function sortItems(operation) { + return { + kind: "transformation", + type: "sort_items", + reference: sortItems, + async: false, + operation, + _run(dataset) { + dataset.value = dataset.value.sort(this.operation); + return dataset; + } + }; +} + +// src/actions/startsWith/startsWith.ts +function startsWith(requirement, message) { + return { + kind: "validation", + type: "starts_with", + reference: startsWith, + async: false, + expects: `"${requirement}"`, + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !dataset.value.startsWith(this.requirement)) { + _addIssue(this, "start", dataset, config2, { + received: `"${dataset.value.slice(0, this.requirement.length)}"` + }); + } + return dataset; + } + }; +} + +// src/actions/toLowerCase/toLowerCase.ts +function toLowerCase() { + return { + kind: "transformation", + type: "to_lower_case", + reference: toLowerCase, + async: false, + _run(dataset) { + dataset.value = dataset.value.toLowerCase(); + return dataset; + } + }; +} + +// src/actions/toMaxValue/toMaxValue.ts +function toMaxValue(requirement) { + return { + kind: "transformation", + type: "to_max_value", + reference: toMaxValue, + async: false, + requirement, + _run(dataset) { + dataset.value = dataset.value > this.requirement ? this.requirement : dataset.value; + return dataset; + } + }; +} + +// src/actions/toMinValue/toMinValue.ts +function toMinValue(requirement) { + return { + kind: "transformation", + type: "to_min_value", + reference: toMinValue, + async: false, + requirement, + _run(dataset) { + dataset.value = dataset.value < this.requirement ? this.requirement : dataset.value; + return dataset; + } + }; +} + +// src/actions/toUpperCase/toUpperCase.ts +function toUpperCase() { + return { + kind: "transformation", + type: "to_upper_case", + reference: toUpperCase, + async: false, + _run(dataset) { + dataset.value = dataset.value.toUpperCase(); + return dataset; + } + }; +} + +// src/actions/transform/transform.ts +function transform(operation) { + return { + kind: "transformation", + type: "transform", + reference: transform, + async: false, + operation, + _run(dataset) { + dataset.value = this.operation(dataset.value); + return dataset; + } + }; +} + +// src/actions/transform/transformAsync.ts +function transformAsync(operation) { + return { + kind: "transformation", + type: "transform", + reference: transformAsync, + async: true, + operation, + async _run(dataset) { + dataset.value = await this.operation(dataset.value); + return dataset; + } + }; +} + +// src/actions/trim/trim.ts +function trim() { + return { + kind: "transformation", + type: "trim", + reference: trim, + async: false, + _run(dataset) { + dataset.value = dataset.value.trim(); + return dataset; + } + }; +} + +// src/actions/trimEnd/trimEnd.ts +function trimEnd() { + return { + kind: "transformation", + type: "trim_end", + reference: trimEnd, + async: false, + _run(dataset) { + dataset.value = dataset.value.trimEnd(); + return dataset; + } + }; +} + +// src/actions/trimStart/trimStart.ts +function trimStart() { + return { + kind: "transformation", + type: "trim_start", + reference: trimStart, + async: false, + _run(dataset) { + dataset.value = dataset.value.trimStart(); + return dataset; + } + }; +} + +// src/actions/ulid/ulid.ts +function ulid(message) { + return { + kind: "validation", + type: "ulid", + reference: ulid, + async: false, + expects: null, + requirement: ULID_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "ULID", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/url/url.ts +function url(message) { + return { + kind: "validation", + type: "url", + reference: url, + async: false, + expects: null, + requirement(input) { + try { + new URL(input); + return true; + } catch { + return false; + } + }, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement(dataset.value)) { + _addIssue(this, "URL", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/uuid/uuid.ts +function uuid(message) { + return { + kind: "validation", + type: "uuid", + reference: uuid, + async: false, + expects: null, + requirement: UUID_REGEX, + message, + _run(dataset, config2) { + if (dataset.typed && !this.requirement.test(dataset.value)) { + _addIssue(this, "UUID", dataset, config2); + } + return dataset; + } + }; +} + +// src/actions/value/value.ts +function value(requirement, message) { + return { + kind: "validation", + type: "value", + reference: value, + async: false, + expects: requirement instanceof Date ? requirement.toJSON() : _stringify(requirement), + requirement, + message, + _run(dataset, config2) { + if (dataset.typed && !(this.requirement <= dataset.value && this.requirement >= dataset.value)) { + _addIssue(this, "value", dataset, config2, { + received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) + }); + } + return dataset; + } + }; +} + +// src/methods/config/config.ts +function config(schema, config2) { + return { + ...schema, + _run(dataset, config_) { + return schema._run(dataset, { ...config_, ...config2 }); + } + }; +} + +// src/methods/getFallback/getFallback.ts +function getFallback(schema, dataset, config2) { + return typeof schema.fallback === "function" ? ( + // @ts-expect-error + schema.fallback(dataset, config2) + ) : ( + // @ts-expect-error + schema.fallback + ); +} + +// src/methods/fallback/fallback.ts +function fallback(schema, fallback2) { + return { + ...schema, + fallback: fallback2, + _run(dataset, config2) { + const outputDataset = schema._run(dataset, config2); + return outputDataset.issues ? { typed: true, value: getFallback(this, outputDataset, config2) } : outputDataset; + } + }; +} + +// src/methods/fallback/fallbackAsync.ts +function fallbackAsync(schema, fallback2) { + return { + ...schema, + fallback: fallback2, + async: true, + async _run(dataset, config2) { + const outputDataset = await schema._run(dataset, config2); + return outputDataset.issues ? ( + // @ts-expect-error + { typed: true, value: await getFallback(this, outputDataset, config2) } + ) : outputDataset; + } + }; +} + +// src/methods/flatten/flatten.ts +function flatten(issues) { + const flatErrors = {}; + for (const issue of issues) { + if (issue.path) { + const dotPath = getDotPath(issue); + if (dotPath) { + if (!flatErrors.nested) { + flatErrors.nested = {}; + } + if (flatErrors.nested[dotPath]) { + flatErrors.nested[dotPath].push(issue.message); + } else { + flatErrors.nested[dotPath] = [issue.message]; + } + } else { + if (flatErrors.other) { + flatErrors.other.push(issue.message); + } else { + flatErrors.other = [issue.message]; + } + } + } else { + if (flatErrors.root) { + flatErrors.root.push(issue.message); + } else { + flatErrors.root = [issue.message]; + } + } + } + return flatErrors; +} + +// src/methods/forward/forward.ts +function forward(action, pathKeys) { + return { + ...action, + _run(dataset, config2) { + const prevIssues = dataset.issues && [...dataset.issues]; + action._run(dataset, config2); + if (dataset.issues) { + for (const issue of dataset.issues) { + if (!prevIssues?.includes(issue)) { + let pathInput = dataset.value; + for (const key of pathKeys) { + const pathValue = pathInput[key]; + const pathItem = { + type: "unknown", + origin: "value", + input: pathInput, + key, + value: pathValue + }; + if (issue.path) { + issue.path.push(pathItem); + } else { + issue.path = [pathItem]; + } + if (!pathValue) { + break; + } + pathInput = pathValue; + } + } + } + } + return dataset; + } + }; +} + +// src/methods/forward/forwardAsync.ts +function forwardAsync(action, pathKeys) { + return { + ...action, + async: true, + async _run(dataset, config2) { + const prevIssues = dataset.issues && [...dataset.issues]; + await action._run(dataset, config2); + if (dataset.issues) { + for (const issue of dataset.issues) { + if (!prevIssues?.includes(issue)) { + let pathInput = dataset.value; + for (const key of pathKeys) { + const pathValue = pathInput[key]; + const pathItem = { + type: "unknown", + origin: "value", + input: pathInput, + key, + value: pathValue + }; + if (issue.path) { + issue.path.push(pathItem); + } else { + issue.path = [pathItem]; + } + if (!pathValue) { + break; + } + pathInput = pathValue; + } + } + } + } + return dataset; + } + }; +} + +// src/methods/getDefault/getDefault.ts +function getDefault(schema, dataset, config2) { + return typeof schema.default === "function" ? ( + // @ts-expect-error + schema.default(dataset, config2) + ) : ( + // @ts-expect-error + schema.default + ); +} + +// src/methods/getDefaults/getDefaults.ts +function getDefaults(schema) { + if ("entries" in schema) { + const object2 = {}; + for (const key in schema.entries) { + object2[key] = getDefaults(schema.entries[key]); + } + return object2; + } + if ("items" in schema) { + return schema.items.map(getDefaults); + } + return getDefault(schema); +} + +// src/methods/getDefaults/getDefaultsAsync.ts +async function getDefaultsAsync(schema) { + if ("entries" in schema) { + return Object.fromEntries( + await Promise.all( + Object.entries(schema.entries).map(async ([key, value2]) => [ + key, + await getDefaultsAsync(value2) + ]) + ) + ); + } + if ("items" in schema) { + return Promise.all(schema.items.map(getDefaultsAsync)); + } + return getDefault(schema); +} + +// src/methods/getFallbacks/getFallbacks.ts +function getFallbacks(schema) { + if ("entries" in schema) { + const object2 = {}; + for (const key in schema.entries) { + object2[key] = getFallbacks(schema.entries[key]); + } + return object2; + } + if ("items" in schema) { + return schema.items.map(getFallbacks); + } + return getFallback(schema); +} + +// src/methods/getFallbacks/getFallbacksAsync.ts +async function getFallbacksAsync(schema) { + if ("entries" in schema) { + return Object.fromEntries( + await Promise.all( + Object.entries(schema.entries).map(async ([key, value2]) => [ + key, + await getFallbacksAsync(value2) + ]) + ) + ); + } + if ("items" in schema) { + return Promise.all(schema.items.map(getFallbacksAsync)); + } + return getFallback(schema); +} + +// src/methods/is/is.ts +function is(schema, input) { + return !schema._run({ typed: false, value: input }, { abortEarly: true }).issues; +} + +// src/schemas/any/any.ts +function any() { + return { + kind: "schema", + type: "any", + reference: any, + expects: "any", + async: false, + _run(dataset) { + dataset.typed = true; + return dataset; + } + }; +} + +// src/schemas/array/array.ts +function array(item, message) { + return { + kind: "schema", + type: "array", + reference: array, + expects: "Array", + async: false, + item, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < input.length; key++) { + const value2 = input[key]; + const itemDataset = this.item._run({ typed: false, value: value2 }, config2); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/array/arrayAsync.ts +function arrayAsync(item, message) { + return { + kind: "schema", + type: "array", + reference: arrayAsync, + expects: "Array", + async: true, + item, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + input.map((value2) => this.item._run({ typed: false, value: value2 }, config2)) + ); + for (let key = 0; key < itemDatasets.length; key++) { + const itemDataset = itemDatasets[key]; + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: input[key] + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/bigint/bigint.ts +function bigint(message) { + return { + kind: "schema", + type: "bigint", + reference: bigint, + expects: "bigint", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "bigint") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/blob/blob.ts +function blob(message) { + return { + kind: "schema", + type: "blob", + reference: blob, + expects: "Blob", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Blob) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/boolean/boolean.ts +function boolean(message) { + return { + kind: "schema", + type: "boolean", + reference: boolean, + expects: "boolean", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "boolean") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/custom/custom.ts +function custom(check2, message) { + return { + kind: "schema", + type: "custom", + reference: custom, + expects: "unknown", + async: false, + check: check2, + message, + _run(dataset, config2) { + if (this.check(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/custom/customAsync.ts +function customAsync(check2, message) { + return { + kind: "schema", + type: "custom", + reference: customAsync, + expects: "unknown", + async: true, + check: check2, + message, + async _run(dataset, config2) { + if (await this.check(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/date/date.ts +function date(message) { + return { + kind: "schema", + type: "date", + reference: date, + expects: "Date", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Date) { + if (!isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2, { + received: '"Invalid Date"' + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/enum/enum.ts +function enum_(enum__, message) { + const options = Object.entries(enum__).filter(([key]) => isNaN(+key)).map(([, value2]) => value2); + return { + kind: "schema", + type: "enum", + reference: enum_, + expects: _joinExpects(options.map(_stringify), "|"), + async: false, + enum: enum__, + options, + message, + _run(dataset, config2) { + if (this.options.includes(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/file/file.ts +function file(message) { + return { + kind: "schema", + type: "file", + reference: file, + expects: "File", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof File) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/function/function.ts +function function_(message) { + return { + kind: "schema", + type: "function", + reference: function_, + expects: "Function", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "function") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/instance/instance.ts +function instance(class_, message) { + return { + kind: "schema", + type: "instance", + reference: instance, + expects: class_.name, + async: false, + class: class_, + message, + _run(dataset, config2) { + if (dataset.value instanceof this.class) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/intersect/utils/_merge/_merge.ts +function _merge(value1, value2) { + if (typeof value1 === typeof value2) { + if (value1 === value2 || value1 instanceof Date && value2 instanceof Date && +value1 === +value2) { + return { value: value1 }; + } + if (value1 && value2 && value1.constructor === Object && value2.constructor === Object) { + for (const key in value2) { + if (key in value1) { + const dataset = _merge(value1[key], value2[key]); + if (dataset.issue) { + return dataset; + } + value1[key] = dataset.value; + } else { + value1[key] = value2[key]; + } + } + return { value: value1 }; + } + if (Array.isArray(value1) && Array.isArray(value2)) { + if (value1.length === value2.length) { + for (let index = 0; index < value1.length; index++) { + const dataset = _merge(value1[index], value2[index]); + if (dataset.issue) { + return dataset; + } + value1[index] = dataset.value; + } + return { value: value1 }; + } + } + } + return { issue: true }; +} + +// src/schemas/intersect/intersect.ts +function intersect(options, message) { + return { + kind: "schema", + type: "intersect", + reference: intersect, + expects: _joinExpects( + options.map((option) => option.expects), + "&" + ), + async: false, + options, + message, + _run(dataset, config2) { + if (this.options.length) { + const input = dataset.value; + let outputs; + dataset.typed = true; + for (const schema of this.options) { + const optionDataset = schema._run( + { typed: false, value: input }, + config2 + ); + if (optionDataset.issues) { + if (dataset.issues) { + dataset.issues.push(...optionDataset.issues); + } else { + dataset.issues = optionDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!optionDataset.typed) { + dataset.typed = false; + } + if (dataset.typed) { + if (outputs) { + outputs.push(optionDataset.value); + } else { + outputs = [optionDataset.value]; + } + } + } + if (dataset.typed) { + dataset.value = outputs[0]; + for (let index = 1; index < outputs.length; index++) { + const mergeDataset = _merge(dataset.value, outputs[index]); + if (mergeDataset.issue) { + _addIssue(this, "type", dataset, config2, { + received: "unknown" + }); + break; + } + dataset.value = mergeDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/intersect/intersectAsync.ts +function intersectAsync(options, message) { + return { + kind: "schema", + type: "intersect", + reference: intersectAsync, + expects: _joinExpects( + options.map((option) => option.expects), + "&" + ), + async: true, + options, + message, + async _run(dataset, config2) { + if (this.options.length) { + const input = dataset.value; + let outputs; + dataset.typed = true; + const optionDatasets = await Promise.all( + this.options.map( + (schema) => schema._run({ typed: false, value: input }, config2) + ) + ); + for (const optionDataset of optionDatasets) { + if (optionDataset.issues) { + if (dataset.issues) { + dataset.issues.push(...optionDataset.issues); + } else { + dataset.issues = optionDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!optionDataset.typed) { + dataset.typed = false; + } + if (dataset.typed) { + if (outputs) { + outputs.push(optionDataset.value); + } else { + outputs = [optionDataset.value]; + } + } + } + if (dataset.typed) { + dataset.value = outputs[0]; + for (let index = 1; index < outputs.length; index++) { + const mergeDataset = _merge(dataset.value, outputs[index]); + if (mergeDataset.issue) { + _addIssue(this, "type", dataset, config2, { + received: "unknown" + }); + break; + } + dataset.value = mergeDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/lazy/lazy.ts +function lazy(getter) { + return { + kind: "schema", + type: "lazy", + reference: lazy, + expects: "unknown", + async: false, + getter, + _run(dataset, config2) { + return this.getter(dataset.value)._run(dataset, config2); + } + }; +} + +// src/schemas/lazy/lazyAsync.ts +function lazyAsync(getter) { + return { + kind: "schema", + type: "lazy", + reference: lazyAsync, + expects: "unknown", + async: true, + getter, + async _run(dataset, config2) { + return (await this.getter(dataset.value))._run(dataset, config2); + } + }; +} + +// src/schemas/literal/literal.ts +function literal(literal_, message) { + return { + kind: "schema", + type: "literal", + reference: literal, + expects: _stringify(literal_), + async: false, + literal: literal_, + message, + _run(dataset, config2) { + if (dataset.value === this.literal) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseObject/looseObject.ts +function looseObject(entries, message) { + return { + kind: "schema", + type: "loose_object", + reference: looseObject, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + dataset.value[key] = input[key]; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseObject/looseObjectAsync.ts +function looseObjectAsync(entries, message) { + return { + kind: "schema", + type: "loose_object", + reference: looseObjectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + dataset.value[key] = input[key]; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseTuple/looseTuple.ts +function looseTuple(items, message) { + return { + kind: "schema", + type: "loose_tuple", + reference: looseTuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + dataset.value.push(input[key]); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/looseTuple/looseTupleAsync.ts +function looseTupleAsync(items, message) { + return { + kind: "schema", + type: "loose_tuple", + reference: looseTupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + dataset.value.push(input[key]); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/map/map.ts +function map(key, value2, message) { + return { + kind: "schema", + type: "map", + reference: map, + expects: "Map", + async: false, + key, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Map) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Map(); + for (const [inputKey, inputValue] of input) { + const keyDataset = this.key._run( + { typed: false, value: inputKey }, + config2 + ); + if (keyDataset.issues) { + const pathItem = { + type: "map", + origin: "key", + input, + key: inputKey, + value: inputValue + }; + for (const issue of keyDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + const valueDataset = this.value._run( + { typed: false, value: inputValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "map", + origin: "value", + input, + key: inputKey, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + dataset.value.set(keyDataset.value, valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/map/mapAsync.ts +function mapAsync(key, value2, message) { + return { + kind: "schema", + type: "map", + reference: mapAsync, + expects: "Map", + async: true, + key, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Map) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Map(); + const datasets = await Promise.all( + [...input].map( + ([inputKey, inputValue]) => Promise.all([ + inputKey, + inputValue, + this.key._run({ typed: false, value: inputKey }, config2), + this.value._run({ typed: false, value: inputValue }, config2) + ]) + ) + ); + for (const [ + inputKey, + inputValue, + keyDataset, + valueDataset + ] of datasets) { + if (keyDataset.issues) { + const pathItem = { + type: "map", + origin: "key", + input, + key: inputKey, + value: inputValue + }; + for (const issue of keyDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (valueDataset.issues) { + const pathItem = { + type: "map", + origin: "value", + input, + key: inputKey, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + dataset.value.set(keyDataset.value, valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/nan/nan.ts +function nan(message) { + return { + kind: "schema", + type: "nan", + reference: nan, + expects: "NaN", + async: false, + message, + _run(dataset, config2) { + if (Number.isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/never/never.ts +function never(message) { + return { + kind: "schema", + type: "never", + reference: never, + expects: "never", + async: false, + message, + _run(dataset, config2) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + }; +} + +// src/schemas/nonNullable/nonNullable.ts +function nonNullable(wrapped, message) { + return { + kind: "schema", + type: "non_nullable", + reference: nonNullable, + expects: "!null", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === null) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullable/nonNullableAsync.ts +function nonNullableAsync(wrapped, message) { + return { + kind: "schema", + type: "non_nullable", + reference: nonNullableAsync, + expects: "!null", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === null) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullish/nonNullish.ts +function nonNullish(wrapped, message) { + return { + kind: "schema", + type: "non_nullish", + reference: nonNullish, + expects: "(!null & !undefined)", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonNullish/nonNullishAsync.ts +function nonNullishAsync(wrapped, message) { + return { + kind: "schema", + type: "non_nullish", + reference: nonNullishAsync, + expects: "(!null & !undefined)", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonOptional/nonOptional.ts +function nonOptional(wrapped, message) { + return { + kind: "schema", + type: "non_optional", + reference: nonOptional, + expects: "!undefined", + async: false, + wrapped, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/nonOptional/nonOptionalAsync.ts +function nonOptionalAsync(wrapped, message) { + return { + kind: "schema", + type: "non_optional", + reference: nonOptionalAsync, + expects: "!undefined", + async: true, + wrapped, + message, + async _run(dataset, config2) { + if (dataset.value === void 0) { + _addIssue(this, "type", dataset, config2); + return dataset; + } + return this.wrapped._run(dataset, config2); + } + }; +} + +// src/schemas/null/null.ts +function null_(message) { + return { + kind: "schema", + type: "null", + reference: null_, + expects: "null", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === null) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/nullable/nullable.ts +function nullable(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullable", + reference: nullable, + expects: `(${wrapped.expects} | null)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === null) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullable/nullableAsync.ts +function nullableAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullable", + reference: nullableAsync, + expects: `(${wrapped.expects} | null)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === null) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullish/nullish.ts +function nullish(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullish", + reference: nullish, + expects: `(${wrapped.expects} | null | undefined)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null || dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/nullish/nullishAsync.ts +function nullishAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "nullish", + reference: nullishAsync, + expects: `(${wrapped.expects} | null | undefined)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === null || dataset.value === void 0) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === null || dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/number/number.ts +function number(message) { + return { + kind: "schema", + type: "number", + reference: number, + expects: "number", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "number" && !isNaN(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/object/object.ts +function object(entries, message) { + return { + kind: "schema", + type: "object", + reference: object, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/object/objectAsync.ts +function objectAsync(entries, message) { + return { + kind: "schema", + type: "object", + reference: objectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/objectWithRest/objectWithRest.ts +function objectWithRest(entries, rest, message) { + return { + kind: "schema", + type: "object_with_rest", + reference: objectWithRest, + expects: "Object", + async: false, + entries, + rest, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (_isValidObjectKey(input, key) && !(key in this.entries)) { + const value2 = input[key]; + const valueDataset = this.rest._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value[key] = valueDataset.value; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/objectWithRest/objectWithRestAsync.ts +function objectWithRestAsync(entries, rest, message) { + return { + kind: "schema", + type: "object_with_rest", + reference: objectWithRestAsync, + expects: "Object", + async: true, + entries, + rest, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const [normalDatasets, restDatasets] = await Promise.all([ + // Parse schema of each normal entry + // Hint: We do not distinguish between missing and `undefined` entries. + // The reason for this decision is that it reduces the bundle size, and + // we also expect that most users will expect this behavior. + Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ), + // Parse other entries with rest schema + // Hint: We exclude specific keys for security reasons + Promise.all( + Object.entries(input).filter( + ([key]) => _isValidObjectKey(input, key) && !(key in this.entries) + ).map( + async ([key, value2]) => [ + key, + value2, + await this.rest._run({ typed: false, value: value2 }, config2) + ] + ) + ) + ]); + for (const [key, value2, valueDataset] of normalDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const [key, value2, valueDataset] of restDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value[key] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/optional/optional.ts +function optional(wrapped, ...args) { + const schema = { + kind: "schema", + type: "optional", + reference: optional, + expects: `(${wrapped.expects} | undefined)`, + async: false, + wrapped, + _run(dataset, config2) { + if (dataset.value === void 0) { + if ("default" in this) { + dataset.value = getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/optional/optionalAsync.ts +function optionalAsync(wrapped, ...args) { + const schema = { + kind: "schema", + type: "optional", + reference: optionalAsync, + expects: `(${wrapped.expects} | undefined)`, + async: true, + wrapped, + async _run(dataset, config2) { + if (dataset.value === void 0) { + if ("default" in this) { + dataset.value = await getDefault( + this, + dataset, + config2 + ); + } + if (dataset.value === void 0) { + dataset.typed = true; + return dataset; + } + } + return this.wrapped._run(dataset, config2); + } + }; + if (0 in args) { + schema.default = args[0]; + } + return schema; +} + +// src/schemas/picklist/picklist.ts +function picklist(options, message) { + return { + kind: "schema", + type: "picklist", + reference: picklist, + expects: _joinExpects(options.map(_stringify), "|"), + async: false, + options, + message, + _run(dataset, config2) { + if (this.options.includes(dataset.value)) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/promise/promise.ts +function promise(message) { + return { + kind: "schema", + type: "promise", + reference: promise, + expects: "Promise", + async: false, + message, + _run(dataset, config2) { + if (dataset.value instanceof Promise) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/record/record.ts +function record(key, value2, message) { + return { + kind: "schema", + type: "record", + reference: record, + expects: "Object", + async: false, + key, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const entryKey in input) { + if (_isValidObjectKey(input, entryKey)) { + const entryValue = input[entryKey]; + const keyDataset = this.key._run( + { typed: false, value: entryKey }, + config2 + ); + if (keyDataset.issues) { + const pathItem = { + type: "object", + origin: "key", + input, + key: entryKey, + value: entryValue + }; + for (const issue of keyDataset.issues) { + issue.path = [pathItem]; + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + const valueDataset = this.value._run( + { typed: false, value: entryValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key: entryKey, + value: entryValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + if (keyDataset.typed) { + dataset.value[keyDataset.value] = valueDataset.value; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/record/recordAsync.ts +function recordAsync(key, value2, message) { + return { + kind: "schema", + type: "record", + reference: recordAsync, + expects: "Object", + async: true, + key, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const datasets = await Promise.all( + Object.entries(input).filter(([key2]) => _isValidObjectKey(input, key2)).map( + ([entryKey, entryValue]) => Promise.all([ + entryKey, + entryValue, + this.key._run({ typed: false, value: entryKey }, config2), + this.value._run({ typed: false, value: entryValue }, config2) + ]) + ) + ); + for (const [ + entryKey, + entryValue, + keyDataset, + valueDataset + ] of datasets) { + if (keyDataset.issues) { + const pathItem = { + type: "object", + origin: "key", + input, + key: entryKey, + value: entryValue + }; + for (const issue of keyDataset.issues) { + issue.path = [pathItem]; + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = keyDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key: entryKey, + value: entryValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!keyDataset.typed || !valueDataset.typed) { + dataset.typed = false; + } + if (keyDataset.typed) { + dataset.value[keyDataset.value] = valueDataset.value; + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/set/set.ts +function set(value2, message) { + return { + kind: "schema", + type: "set", + reference: set, + expects: "Set", + async: false, + value: value2, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Set) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Set(); + for (const inputValue of input) { + const valueDataset = this.value._run( + { typed: false, value: inputValue }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "set", + origin: "value", + input, + key: null, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value.add(valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/set/setAsync.ts +function setAsync(value2, message) { + return { + kind: "schema", + type: "set", + reference: setAsync, + expects: "Set", + async: true, + value: value2, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input instanceof Set) { + dataset.typed = true; + dataset.value = /* @__PURE__ */ new Set(); + const valueDatasets = await Promise.all( + [...input].map( + async (inputValue) => [ + inputValue, + await this.value._run( + { typed: false, value: inputValue }, + config2 + ) + ] + ) + ); + for (const [inputValue, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "set", + origin: "value", + input, + key: null, + value: inputValue + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + dataset.value.add(valueDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictObject/strictObject.ts +function strictObject(entries, message) { + return { + kind: "schema", + type: "strict_object", + reference: strictObject, + expects: "Object", + async: false, + entries, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + for (const key in this.entries) { + const value2 = input[key]; + const valueDataset = this.entries[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (!(key in this.entries)) { + const value2 = input[key]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "object", + origin: "value", + input, + key, + value: value2 + } + ] + }); + break; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictObject/strictObjectAsync.ts +function strictObjectAsync(entries, message) { + return { + kind: "schema", + type: "strict_object", + reference: strictObjectAsync, + expects: "Object", + async: true, + entries, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + dataset.typed = true; + dataset.value = {}; + const valueDatasets = await Promise.all( + Object.entries(this.entries).map(async ([key, schema]) => { + const value2 = input[key]; + return [ + key, + value2, + await schema._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, valueDataset] of valueDatasets) { + if (valueDataset.issues) { + const pathItem = { + type: "object", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of valueDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = valueDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!valueDataset.typed) { + dataset.typed = false; + } + if (valueDataset.value !== void 0 || key in input) { + dataset.value[key] = valueDataset.value; + } + } + if (!dataset.issues || !config2.abortEarly) { + for (const key in input) { + if (!(key in this.entries)) { + const value2 = input[key]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "object", + origin: "value", + input, + key, + value: value2 + } + ] + }); + break; + } + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictTuple/strictTuple.ts +function strictTuple(items, message) { + return { + kind: "schema", + type: "strict_tuple", + reference: strictTuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!(dataset.issues && config2.abortEarly) && this.items.length < input.length) { + const value2 = input[items.length]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "array", + origin: "value", + input, + key: this.items.length, + value: value2 + } + ] + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/strictTuple/strictTupleAsync.ts +function strictTupleAsync(items, message) { + return { + kind: "schema", + type: "strict_tuple", + reference: strictTupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!(dataset.issues && config2.abortEarly) && this.items.length < input.length) { + const value2 = input[items.length]; + _addIssue(this, "type", dataset, config2, { + input: value2, + expected: "never", + path: [ + { + type: "array", + origin: "value", + input, + key: this.items.length, + value: value2 + } + ] + }); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/string/string.ts +function string(message) { + return { + kind: "schema", + type: "string", + reference: string, + expects: "string", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "string") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/symbol/symbol.ts +function symbol(message) { + return { + kind: "schema", + type: "symbol", + reference: symbol, + expects: "symbol", + async: false, + message, + _run(dataset, config2) { + if (typeof dataset.value === "symbol") { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tuple/tuple.ts +function tuple(items, message) { + return { + kind: "schema", + type: "tuple", + reference: tuple, + expects: "Array", + async: false, + items, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tuple/tupleAsync.ts +function tupleAsync(items, message) { + return { + kind: "schema", + type: "tuple", + reference: tupleAsync, + expects: "Array", + async: true, + items, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const itemDatasets = await Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ); + for (const [key, value2, itemDataset] of itemDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tupleWithRest/tupleWithRest.ts +function tupleWithRest(items, rest, message) { + return { + kind: "schema", + type: "tuple_with_rest", + reference: tupleWithRest, + expects: "Array", + async: false, + items, + rest, + message, + _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + for (let key = 0; key < this.items.length; key++) { + const value2 = input[key]; + const itemDataset = this.items[key]._run( + { typed: false, value: value2 }, + config2 + ); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (let key = this.items.length; key < input.length; key++) { + const value2 = input[key]; + const itemDataset = this.rest._run({ typed: false, value: value2 }, config2); + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/tupleWithRest/tupleWithRestAsync.ts +function tupleWithRestAsync(items, rest, message) { + return { + kind: "schema", + type: "tuple_with_rest", + reference: tupleWithRestAsync, + expects: "Array", + async: true, + items, + rest, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (Array.isArray(input)) { + dataset.typed = true; + dataset.value = []; + const [normalDatasets, restDatasets] = await Promise.all([ + // Parse schema of each normal item + Promise.all( + this.items.map(async (item, key) => { + const value2 = input[key]; + return [ + key, + value2, + await item._run({ typed: false, value: value2 }, config2) + ]; + }) + ), + // Parse other items with rest schema + Promise.all( + input.slice(this.items.length).map(async (value2, key) => { + return [ + key + this.items.length, + value2, + await this.rest._run({ typed: false, value: value2 }, config2) + ]; + }) + ) + ]); + for (const [key, value2, itemDataset] of normalDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + if (!dataset.issues || !config2.abortEarly) { + for (const [key, value2, itemDataset] of restDatasets) { + if (itemDataset.issues) { + const pathItem = { + type: "array", + origin: "value", + input, + key, + value: value2 + }; + for (const issue of itemDataset.issues) { + if (issue.path) { + issue.path.unshift(pathItem); + } else { + issue.path = [pathItem]; + } + dataset.issues?.push(issue); + } + if (!dataset.issues) { + dataset.issues = itemDataset.issues; + } + if (config2.abortEarly) { + dataset.typed = false; + break; + } + } + if (!itemDataset.typed) { + dataset.typed = false; + } + dataset.value.push(itemDataset.value); + } + } + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/undefined/undefined.ts +function undefined_(message) { + return { + kind: "schema", + type: "undefined", + reference: undefined_, + expects: "undefined", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/union/utils/_subIssues/_subIssues.ts +function _subIssues(datasets) { + let issues; + if (datasets) { + for (const dataset of datasets) { + if (issues) { + issues.push(...dataset.issues); + } else { + issues = dataset.issues; + } + } + } + return issues; +} + +// src/schemas/union/union.ts +function union(options, message) { + return { + kind: "schema", + type: "union", + reference: union, + expects: _joinExpects( + options.map((option) => option.expects), + "|" + ), + async: false, + options, + message, + _run(dataset, config2) { + let validDataset; + let typedDatasets; + let untypedDatasets; + for (const schema of this.options) { + const optionDataset = schema._run( + { typed: false, value: dataset.value }, + config2 + ); + if (optionDataset.typed) { + if (optionDataset.issues) { + if (typedDatasets) { + typedDatasets.push(optionDataset); + } else { + typedDatasets = [optionDataset]; + } + } else { + validDataset = optionDataset; + break; + } + } else { + if (untypedDatasets) { + untypedDatasets.push(optionDataset); + } else { + untypedDatasets = [optionDataset]; + } + } + } + if (validDataset) { + return validDataset; + } + if (typedDatasets) { + if (typedDatasets.length === 1) { + return typedDatasets[0]; + } + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(typedDatasets) + }); + dataset.typed = true; + } else if (untypedDatasets?.length === 1) { + return untypedDatasets[0]; + } else { + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(untypedDatasets) + }); + } + return dataset; + } + }; +} + +// src/schemas/union/unionAsync.ts +function unionAsync(options, message) { + return { + kind: "schema", + type: "union", + reference: unionAsync, + expects: _joinExpects( + options.map((option) => option.expects), + "|" + ), + async: true, + options, + message, + async _run(dataset, config2) { + let validDataset; + let typedDatasets; + let untypedDatasets; + for (const schema of this.options) { + const optionDataset = await schema._run( + { typed: false, value: dataset.value }, + config2 + ); + if (optionDataset.typed) { + if (optionDataset.issues) { + if (typedDatasets) { + typedDatasets.push(optionDataset); + } else { + typedDatasets = [optionDataset]; + } + } else { + validDataset = optionDataset; + break; + } + } else { + if (untypedDatasets) { + untypedDatasets.push(optionDataset); + } else { + untypedDatasets = [optionDataset]; + } + } + } + if (validDataset) { + return validDataset; + } + if (typedDatasets) { + if (typedDatasets.length === 1) { + return typedDatasets[0]; + } + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(typedDatasets) + }); + dataset.typed = true; + } else if (untypedDatasets?.length === 1) { + return untypedDatasets[0]; + } else { + _addIssue(this, "type", dataset, config2, { + issues: _subIssues(untypedDatasets) + }); + } + return dataset; + } + }; +} + +// src/schemas/unknown/unknown.ts +function unknown() { + return { + kind: "schema", + type: "unknown", + reference: unknown, + expects: "unknown", + async: false, + _run(dataset) { + dataset.typed = true; + return dataset; + } + }; +} + +// src/schemas/variant/utils/_discriminators/_discriminators.ts +function _discriminators(key, options, list = []) { + for (const schema of options) { + if (schema.type === "variant") { + _discriminators(key, schema.options, list); + } else { + list.push(schema.entries[key].expects); + } + } + return list; +} + +// src/schemas/variant/variant.ts +function variant(key, options, message) { + let expectedDiscriminators; + return { + kind: "schema", + type: "variant", + reference: variant, + expects: "Object", + async: false, + key, + options, + message, + _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + const discriminator = input[this.key]; + if (this.key in input) { + let outputDataset; + for (const schema of this.options) { + if (schema.type === "variant" || !schema.entries[this.key]._run( + { typed: false, value: discriminator }, + config2 + ).issues) { + const optionDataset = schema._run( + { typed: false, value: input }, + config2 + ); + if (!optionDataset.issues) { + return optionDataset; + } + if (!outputDataset || !outputDataset.typed && optionDataset.typed) { + outputDataset = optionDataset; + } + } + } + if (outputDataset) { + return outputDataset; + } + } + if (!expectedDiscriminators) { + expectedDiscriminators = _joinExpects( + _discriminators(this.key, this.options), + "|" + ); + } + _addIssue(this, "type", dataset, config2, { + input: discriminator, + expected: expectedDiscriminators, + path: [ + { + type: "object", + origin: "value", + input, + key: this.key, + value: discriminator + } + ] + }); + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/variant/variantAsync.ts +function variantAsync(key, options, message) { + let expectedDiscriminators; + return { + kind: "schema", + type: "variant", + reference: variantAsync, + expects: "Object", + async: true, + key, + options, + message, + async _run(dataset, config2) { + const input = dataset.value; + if (input && typeof input === "object") { + const discriminator = input[this.key]; + if (this.key in input) { + let outputDataset; + for (const schema of this.options) { + if (schema.type === "variant" || !(await schema.entries[this.key]._run( + { typed: false, value: discriminator }, + config2 + )).issues) { + const optionDataset = await schema._run( + { typed: false, value: input }, + config2 + ); + if (!optionDataset.issues) { + return optionDataset; + } + if (!outputDataset || !outputDataset.typed && optionDataset.typed) { + outputDataset = optionDataset; + } + } + } + if (outputDataset) { + return outputDataset; + } + } + if (!expectedDiscriminators) { + expectedDiscriminators = _joinExpects( + _discriminators(this.key, this.options), + "|" + ); + } + _addIssue(this, "type", dataset, config2, { + input: discriminator, + expected: expectedDiscriminators, + path: [ + { + type: "object", + origin: "value", + input, + key: this.key, + value: discriminator + } + ] + }); + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/schemas/void/void.ts +function void_(message) { + return { + kind: "schema", + type: "void", + reference: void_, + expects: "void", + async: false, + message, + _run(dataset, config2) { + if (dataset.value === void 0) { + dataset.typed = true; + } else { + _addIssue(this, "type", dataset, config2); + } + return dataset; + } + }; +} + +// src/methods/keyof/keyof.ts +function keyof(schema, message) { + return picklist(Object.keys(schema.entries), message); +} + +// src/methods/omit/omit.ts +function omit(schema, keys) { + const entries = { + ...schema.entries + }; + for (const key of keys) { + delete entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/parse/parse.ts +function parse(schema, input, config2) { + const dataset = schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + if (dataset.issues) { + throw new ValiError(dataset.issues); + } + return dataset.value; +} + +// src/methods/parse/parseAsync.ts +async function parseAsync(schema, input, config2) { + const dataset = await schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + if (dataset.issues) { + throw new ValiError(dataset.issues); + } + return dataset.value; +} + +// src/methods/parser/parser.ts +function parser(schema, config2) { + const func = (input) => parse(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/parser/parserAsync.ts +function parserAsync(schema, config2) { + const func = (input) => parseAsync(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/partial/partial.ts +function partial(schema, keys) { + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? optional(schema.entries[key]) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/partial/partialAsync.ts +function partialAsync(schema, keys) { + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? optionalAsync(schema.entries[key]) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/pick/pick.ts +function pick(schema, keys) { + const entries = {}; + for (const key of keys) { + entries[key] = schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/pipe/pipe.ts +function pipe(...pipe2) { + return { + ...pipe2[0], + pipe: pipe2, + _run(dataset, config2) { + for (const item of pipe2) { + if (item.kind !== "metadata") { + if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { + dataset.typed = false; + break; + } + if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) { + dataset = item._run(dataset, config2); + } + } + } + return dataset; + } + }; +} + +// src/methods/pipe/pipeAsync.ts +function pipeAsync(...pipe2) { + return { + ...pipe2[0], + pipe: pipe2, + async: true, + async _run(dataset, config2) { + for (const item of pipe2) { + if (item.kind !== "metadata") { + if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { + dataset.typed = false; + break; + } + if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) { + dataset = await item._run(dataset, config2); + } + } + } + return dataset; + } + }; +} + +// src/methods/required/required.ts +function required(schema, arg2, arg3) { + const keys = Array.isArray(arg2) ? arg2 : void 0; + const message = Array.isArray(arg2) ? arg3 : arg2; + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? nonOptional(schema.entries[key], message) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/required/requiredAsync.ts +function requiredAsync(schema, arg2, arg3) { + const keys = Array.isArray(arg2) ? arg2 : void 0; + const message = Array.isArray(arg2) ? arg3 : arg2; + const entries = {}; + for (const key in schema.entries) { + entries[key] = !keys || keys.includes(key) ? nonOptionalAsync(schema.entries[key], message) : schema.entries[key]; + } + return { ...schema, entries }; +} + +// src/methods/safeParse/safeParse.ts +function safeParse(schema, input, config2) { + const dataset = schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + return { + typed: dataset.typed, + success: !dataset.issues, + output: dataset.value, + issues: dataset.issues + }; +} + +// src/methods/safeParse/safeParseAsync.ts +async function safeParseAsync(schema, input, config2) { + const dataset = await schema._run( + { typed: false, value: input }, + getGlobalConfig(config2) + ); + return { + typed: dataset.typed, + success: !dataset.issues, + output: dataset.value, + issues: dataset.issues + }; +} + +// src/methods/safeParser/safeParser.ts +function safeParser(schema, config2) { + const func = (input) => safeParse(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/safeParser/safeParserAsync.ts +function safeParserAsync(schema, config2) { + const func = (input) => safeParseAsync(schema, input, config2); + func.schema = schema; + func.config = config2; + return func; +} + +// src/methods/unwrap/unwrap.ts +function unwrap(schema) { + return schema.wrapped; +} +export { + BASE64_REGEX, + BIC_REGEX, + CUID2_REGEX, + DECIMAL_REGEX, + EMAIL_REGEX, + EMOJI_REGEX, + HEXADECIMAL_REGEX, + HEX_COLOR_REGEX, + IMEI_REGEX, + IPV4_REGEX, + IPV6_REGEX, + IP_REGEX, + ISO_DATE_REGEX, + ISO_DATE_TIME_REGEX, + ISO_TIMESTAMP_REGEX, + ISO_TIME_REGEX, + ISO_TIME_SECOND_REGEX, + ISO_WEEK_REGEX, + MAC48_REGEX, + MAC64_REGEX, + MAC_REGEX, + OCTAL_REGEX, + ULID_REGEX, + UUID_REGEX, + ValiError, + _addIssue, + _isLuhnAlgo, + _isValidObjectKey, + _joinExpects, + _stringify, + any, + array, + arrayAsync, + awaitAsync, + base64, + bic, + bigint, + blob, + boolean, + brand, + bytes, + check, + checkAsync, + checkItems, + config, + creditCard, + cuid2, + custom, + customAsync, + date, + decimal, + deleteGlobalConfig, + deleteGlobalMessage, + deleteSchemaMessage, + deleteSpecificMessage, + description, + email, + emoji, + empty, + endsWith, + entriesFromList, + enum_ as enum, + enum_, + everyItem, + excludes, + fallback, + fallbackAsync, + file, + filterItems, + findItem, + finite, + flatten, + forward, + forwardAsync, + function_ as function, + function_, + getDefault, + getDefaults, + getDefaultsAsync, + getDotPath, + getFallback, + getFallbacks, + getFallbacksAsync, + getGlobalConfig, + getGlobalMessage, + getSchemaMessage, + getSpecificMessage, + hash, + hexColor, + hexadecimal, + imei, + includes, + instance, + integer, + intersect, + intersectAsync, + ip, + ipv4, + ipv6, + is, + isOfKind, + isOfType, + isValiError, + isoDate, + isoDateTime, + isoTime, + isoTimeSecond, + isoTimestamp, + isoWeek, + keyof, + lazy, + lazyAsync, + length, + literal, + looseObject, + looseObjectAsync, + looseTuple, + looseTupleAsync, + mac, + mac48, + mac64, + map, + mapAsync, + mapItems, + maxBytes, + maxLength, + maxSize, + maxValue, + mimeType, + minBytes, + minLength, + minSize, + minValue, + multipleOf, + nan, + never, + nonEmpty, + nonNullable, + nonNullableAsync, + nonNullish, + nonNullishAsync, + nonOptional, + nonOptionalAsync, + normalize, + notBytes, + notLength, + notSize, + notValue, + null_ as null, + null_, + nullable, + nullableAsync, + nullish, + nullishAsync, + number, + object, + objectAsync, + objectWithRest, + objectWithRestAsync, + octal, + omit, + optional, + optionalAsync, + parse, + parseAsync, + parser, + parserAsync, + partial, + partialAsync, + partialCheck, + partialCheckAsync, + pick, + picklist, + pipe, + pipeAsync, + promise, + rawCheck, + rawCheckAsync, + rawTransform, + rawTransformAsync, + readonly, + record, + recordAsync, + reduceItems, + regex, + required, + requiredAsync, + safeInteger, + safeParse, + safeParseAsync, + safeParser, + safeParserAsync, + set, + setAsync, + setGlobalConfig, + setGlobalMessage, + setSchemaMessage, + setSpecificMessage, + size, + someItem, + sortItems, + startsWith, + strictObject, + strictObjectAsync, + strictTuple, + strictTupleAsync, + string, + symbol, + toLowerCase, + toMaxValue, + toMinValue, + toUpperCase, + transform, + transformAsync, + trim, + trimEnd, + trimStart, + tuple, + tupleAsync, + tupleWithRest, + tupleWithRestAsync, + ulid, + undefined_ as undefined, + undefined_, + union, + unionAsync, + unknown, + unwrap, + url, + uuid, + value, + variant, + variantAsync, + void_ as void, + void_ +}; diff --git a/src/libMPC/node_modules/valibot/dist/index.min.cjs b/src/libMPC/node_modules/valibot/dist/index.min.cjs new file mode 100644 index 0000000..08a0188 --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.min.cjs @@ -0,0 +1 @@ +"use strict";var q=Object.defineProperty;var us=Object.getOwnPropertyDescriptor;var rs=Object.getOwnPropertyNames;var Is=Object.prototype.hasOwnProperty;var os=(t,n)=>{for(var e in n)q(t,e,{get:n[e],enumerable:!0})},is=(t,n,e,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of rs(n))!Is.call(t,u)&&u!==e&&q(t,u,{get:()=>n[u],enumerable:!(s=us(n,u))||s.enumerable});return t};var as=t=>is(q({},"__esModule",{value:!0}),t);var Xs={};os(Xs,{BASE64_REGEX:()=>D,BIC_REGEX:()=>N,CUID2_REGEX:()=>W,DECIMAL_REGEX:()=>V,EMAIL_REGEX:()=>C,EMOJI_REGEX:()=>L,HEXADECIMAL_REGEX:()=>K,HEX_COLOR_REGEX:()=>$,IMEI_REGEX:()=>z,IPV4_REGEX:()=>F,IPV6_REGEX:()=>U,IP_REGEX:()=>G,ISO_DATE_REGEX:()=>X,ISO_DATE_TIME_REGEX:()=>H,ISO_TIMESTAMP_REGEX:()=>Q,ISO_TIME_REGEX:()=>J,ISO_TIME_SECOND_REGEX:()=>Z,ISO_WEEK_REGEX:()=>Y,MAC48_REGEX:()=>ee,MAC64_REGEX:()=>ne,MAC_REGEX:()=>te,OCTAL_REGEX:()=>se,ULID_REGEX:()=>ue,UUID_REGEX:()=>re,ValiError:()=>h,_addIssue:()=>r,_isLuhnAlgo:()=>b,_isValidObjectKey:()=>l,_joinExpects:()=>d,_stringify:()=>f,any:()=>Jn,array:()=>Zn,arrayAsync:()=>Qn,awaitAsync:()=>ke,base64:()=>he,bic:()=>xe,bigint:()=>Yn,blob:()=>et,boolean:()=>nt,brand:()=>Oe,bytes:()=>we,check:()=>ge,checkAsync:()=>Se,checkItems:()=>Be,config:()=>bs,creditCard:()=>Ae,cuid2:()=>be,custom:()=>tt,customAsync:()=>st,date:()=>ut,decimal:()=>Ee,deleteGlobalConfig:()=>ps,deleteGlobalMessage:()=>Ts,deleteSchemaMessage:()=>ds,deleteSpecificMessage:()=>ls,description:()=>Me,email:()=>Pe,emoji:()=>je,empty:()=>Re,endsWith:()=>ve,entriesFromList:()=>hs,enum:()=>rt,enum_:()=>rt,everyItem:()=>_e,excludes:()=>qe,fallback:()=>Es,fallbackAsync:()=>Ms,file:()=>It,filterItems:()=>De,findItem:()=>Ne,finite:()=>We,flatten:()=>Ps,forward:()=>js,forwardAsync:()=>Rs,function:()=>ot,function_:()=>ot,getDefault:()=>y,getDefaults:()=>me,getDefaultsAsync:()=>pe,getDotPath:()=>ae,getFallback:()=>x,getFallbacks:()=>ce,getFallbacksAsync:()=>Te,getGlobalConfig:()=>k,getGlobalMessage:()=>Ie,getSchemaMessage:()=>oe,getSpecificMessage:()=>ie,hash:()=>Ve,hexColor:()=>Le,hexadecimal:()=>Ce,imei:()=>Ke,includes:()=>$e,instance:()=>it,integer:()=>ze,intersect:()=>at,intersectAsync:()=>mt,ip:()=>Fe,ipv4:()=>Ue,ipv6:()=>Ge,is:()=>vs,isOfKind:()=>xs,isOfType:()=>Os,isValiError:()=>ws,isoDate:()=>Xe,isoDateTime:()=>He,isoTime:()=>Je,isoTimeSecond:()=>Ze,isoTimestamp:()=>Qe,isoWeek:()=>Ye,keyof:()=>_s,lazy:()=>pt,lazyAsync:()=>ct,length:()=>en,literal:()=>Tt,looseObject:()=>ft,looseObjectAsync:()=>dt,looseTuple:()=>yt,looseTupleAsync:()=>lt,mac:()=>nn,mac48:()=>tn,mac64:()=>sn,map:()=>kt,mapAsync:()=>ht,mapItems:()=>un,maxBytes:()=>rn,maxLength:()=>In,maxSize:()=>on,maxValue:()=>an,mimeType:()=>mn,minBytes:()=>pn,minLength:()=>cn,minSize:()=>Tn,minValue:()=>fn,multipleOf:()=>dn,nan:()=>xt,never:()=>Ot,nonEmpty:()=>yn,nonNullable:()=>wt,nonNullableAsync:()=>gt,nonNullish:()=>St,nonNullishAsync:()=>Bt,nonOptional:()=>P,nonOptionalAsync:()=>j,normalize:()=>ln,notBytes:()=>kn,notLength:()=>hn,notSize:()=>xn,notValue:()=>On,null:()=>At,null_:()=>At,nullable:()=>bt,nullableAsync:()=>Et,nullish:()=>Mt,nullishAsync:()=>Pt,number:()=>jt,object:()=>Rt,objectAsync:()=>vt,objectWithRest:()=>_t,objectWithRestAsync:()=>qt,octal:()=>wn,omit:()=>qs,optional:()=>R,optionalAsync:()=>v,parse:()=>fe,parseAsync:()=>de,parser:()=>Ds,parserAsync:()=>Ns,partial:()=>Ws,partialAsync:()=>Vs,partialCheck:()=>gn,partialCheckAsync:()=>Sn,pick:()=>Cs,picklist:()=>_,pipe:()=>Ls,pipeAsync:()=>Ks,promise:()=>Dt,rawCheck:()=>Bn,rawCheckAsync:()=>An,rawTransform:()=>bn,rawTransformAsync:()=>En,readonly:()=>Mn,record:()=>Nt,recordAsync:()=>Wt,reduceItems:()=>Pn,regex:()=>jn,required:()=>$s,requiredAsync:()=>zs,safeInteger:()=>Rn,safeParse:()=>ye,safeParseAsync:()=>le,safeParser:()=>Fs,safeParserAsync:()=>Us,set:()=>Vt,setAsync:()=>Ct,setGlobalConfig:()=>ms,setGlobalMessage:()=>cs,setSchemaMessage:()=>fs,setSpecificMessage:()=>ys,size:()=>vn,someItem:()=>_n,sortItems:()=>qn,startsWith:()=>Dn,strictObject:()=>Lt,strictObjectAsync:()=>Kt,strictTuple:()=>$t,strictTupleAsync:()=>zt,string:()=>Ft,symbol:()=>Ut,toLowerCase:()=>Nn,toMaxValue:()=>Wn,toMinValue:()=>Vn,toUpperCase:()=>Cn,transform:()=>Ln,transformAsync:()=>Kn,trim:()=>$n,trimEnd:()=>zn,trimStart:()=>Fn,tuple:()=>Gt,tupleAsync:()=>Xt,tupleWithRest:()=>Ht,tupleWithRestAsync:()=>Jt,ulid:()=>Un,undefined:()=>Zt,undefined_:()=>Zt,union:()=>Qt,unionAsync:()=>Yt,unknown:()=>es,unwrap:()=>Gs,url:()=>Gn,uuid:()=>Xn,value:()=>Hn,variant:()=>ns,variantAsync:()=>ts,void:()=>ss,void_:()=>ss});module.exports=as(Xs);function ke(){return{kind:"transformation",type:"await",reference:ke,async:!0,async _run(t){return t.value=await t.value,t}}}var D=/^(?:[\da-z+/]{4})*(?:[\da-z+/]{2}==|[\da-z+/]{3}=)?$/iu,N=/^[A-Z]{6}(?!00)[\dA-Z]{2}(?:[\dA-Z]{3})?$/u,W=/^[a-z][\da-z]*$/u,V=/^\d+$/u,C=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,L=/^(?:[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}))*)+$/u,K=/^(?:0[hx])?[\da-f]+$/iu,$=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/iu,z=/^\d{15}$|^\d{2}-\d{6}-\d{6}-\d$/u,F=/^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$/u,U=/^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu,G=/^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$|^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){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-f]{4}$|^(?:[\da-f]{2}:){7}[\da-f]{2}$|^(?:[\da-f]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu,se=/^(?:0o)?[0-7]+$/iu,ue=/^[\da-hjkmnp-tv-z]{26}$/iu,re=/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu;var w;function ms(t){w={...w,...t}}function k(t){return{lang:t?.lang??w?.lang,message:t?.message,abortEarly:t?.abortEarly??w?.abortEarly,abortPipeEarly:t?.abortPipeEarly??w?.abortPipeEarly}}function ps(){w=void 0}var B;function cs(t,n){B||(B=new Map),B.set(n,t)}function Ie(t){return B?.get(t)}function Ts(t){B?.delete(t)}var A;function fs(t,n){A||(A=new Map),A.set(n,t)}function oe(t){return A?.get(t)}function ds(t){A?.delete(t)}var O;function ys(t,n,e){O||(O=new Map),O.get(t)||O.set(t,new Map),O.get(t).set(e,n)}function ie(t,n){return O?.get(t)?.get(n)}function ls(t,n){O?.get(t)?.delete(n)}function f(t){let n=typeof t;return n==="string"?`"${t}"`:n==="number"||n==="bigint"||n==="boolean"?`${t}`:n==="object"||n==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":n}function r(t,n,e,s,u){let o=u&&"input"in u?u.input:e.value,i=u?.expected??t.expects??null,a=u?.received??f(o),I={kind:t.kind,type:t.type,input:o,expected:i,received:a,message:`Invalid ${n}: ${i?`Expected ${i} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:u?.path,issues:u?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},m=t.kind==="schema",p=u?.message??t.message??ie(t.reference,I.lang)??(m?oe(I.lang):null)??s.message??Ie(I.lang);p&&(I.message=typeof p=="function"?p(I):p),m&&(e.typed=!1),e.issues?e.issues.push(I):e.issues=[I]}var ks=/\D/gu;function b(t){let n=t.replace(ks,""),e=n.length,s=1,u=0;for(;e;){let o=+n[--e];s^=1,u+=s?[0,2,4,6,8,1,3,5,7,9][o]:o}return u%10===0}function l(t,n){return Object.hasOwn(t,n)&&n!=="__proto__"&&n!=="prototype"&&n!=="constructor"}function d(t,n){let e=[...new Set(t)];return e.length>1?`(${e.join(` ${n} `)})`:e[0]??"never"}function hs(t,n){let e={};for(let s of t)e[s]=n;return e}function ae(t){if(t.path){let n="";for(let e of t.path)if(typeof e.key=="string"||typeof e.key=="number")n?n+=`.${e.key}`:n+=e.key;else return null;return n}return null}function xs(t,n){return n.kind===t}function Os(t,n){return n.type===t}function ws(t){return t instanceof h}var h=class extends Error{issues;constructor(n){super(n[0].message),this.name="ValiError",this.issues=n}};function he(t){return{kind:"validation",type:"base64",reference:he,async:!1,expects:null,requirement:D,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"Base64",n,e),n}}}function xe(t){return{kind:"validation",type:"bic",reference:xe,async:!1,expects:null,requirement:N,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"BIC",n,e),n}}}function Oe(t){return{kind:"transformation",type:"brand",reference:Oe,async:!1,name:t,_run(n){return n}}}function we(t,n){return{kind:"validation",type:"bytes",reference:we,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let u=new TextEncoder().encode(e.value).length;u!==this.requirement&&r(this,"bytes",e,s,{received:`${u}`})}return e}}}function ge(t,n){return{kind:"validation",type:"check",reference:ge,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement(e.value)&&r(this,"input",e,s),e}}}function Se(t,n){return{kind:"validation",type:"check",reference:Se,async:!0,expects:null,requirement:t,message:n,async _run(e,s){return e.typed&&!await this.requirement(e.value)&&r(this,"input",e,s),e}}}function Be(t,n){return{kind:"validation",type:"check_items",reference:Be,async:!1,expects:null,requirement:t,message:n,_run(e,s){if(e.typed)for(let u=0;us.test(e))&&b(e)},message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&r(this,"credit card",n,e),n}}}function be(t){return{kind:"validation",type:"cuid2",reference:be,async:!1,expects:null,requirement:W,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"Cuid2",n,e),n}}}function Ee(t){return{kind:"validation",type:"decimal",reference:Ee,async:!1,expects:null,requirement:V,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"decimal",n,e),n}}}function Me(t){return{kind:"metadata",type:"description",reference:Me,description:t}}function Pe(t){return{kind:"validation",type:"email",reference:Pe,expects:null,async:!1,requirement:C,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"email",n,e),n}}}function je(t){return{kind:"validation",type:"emoji",reference:je,async:!1,expects:null,requirement:L,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"emoji",n,e),n}}}function Re(t){return{kind:"validation",type:"empty",reference:Re,async:!1,expects:"0",message:t,_run(n,e){return n.typed&&n.value.length>0&&r(this,"length",n,e,{received:`${n.value.length}`}),n}}}function ve(t,n){return{kind:"validation",type:"ends_with",reference:ve,async:!1,expects:`"${t}"`,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.endsWith(this.requirement)&&r(this,"end",e,s,{received:`"${e.value.slice(-this.requirement.length)}"`}),e}}}function _e(t,n){return{kind:"validation",type:"every_item",reference:_e,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.every(this.requirement)&&r(this,"item",e,s),e}}}function qe(t,n){let e=f(t);return{kind:"validation",type:"excludes",reference:qe,async:!1,expects:`!${e}`,requirement:t,message:n,_run(s,u){return s.typed&&s.value.includes(this.requirement)&&r(this,"content",s,u,{received:e}),s}}}function De(t){return{kind:"transformation",type:"filter_items",reference:De,async:!1,operation:t,_run(n){return n.value=n.value.filter(this.operation),n}}}function Ne(t){return{kind:"transformation",type:"find_item",reference:Ne,async:!1,operation:t,_run(n){return n.value=n.value.find(this.operation),n}}}function We(t){return{kind:"validation",type:"finite",reference:We,async:!1,expects:null,requirement:Number.isFinite,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&r(this,"finite",n,e),n}}}var As={md4:32,md5:32,sha1:40,sha256:64,sha384:96,sha512:128,ripemd128:32,ripemd160:40,tiger128:32,tiger160:40,tiger192:48,crc32:8,crc32b:8,adler32:8};function Ve(t,n){return{kind:"validation",type:"hash",reference:Ve,expects:null,async:!1,requirement:RegExp(t.map(e=>`^[a-f0-9]{${As[e]}}$`).join("|"),"iu"),message:n,_run(e,s){return e.typed&&!this.requirement.test(e.value)&&r(this,"hash",e,s),e}}}function Ce(t){return{kind:"validation",type:"hexadecimal",reference:Ce,async:!1,expects:null,requirement:K,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"hexadecimal",n,e),n}}}function Le(t){return{kind:"validation",type:"hex_color",reference:Le,async:!1,expects:null,requirement:$,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"hex color",n,e),n}}}function Ke(t){return{kind:"validation",type:"imei",reference:Ke,async:!1,expects:null,requirement(n){return z.test(n)&&b(n)},message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&r(this,"IMEI",n,e),n}}}function $e(t,n){let e=f(t);return{kind:"validation",type:"includes",reference:$e,async:!1,expects:e,requirement:t,message:n,_run(s,u){return s.typed&&!s.value.includes(this.requirement)&&r(this,"content",s,u,{received:`!${e}`}),s}}}function ze(t){return{kind:"validation",type:"integer",reference:ze,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&r(this,"integer",n,e),n}}}function Fe(t){return{kind:"validation",type:"ip",reference:Fe,async:!1,expects:null,requirement:G,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"IP",n,e),n}}}function Ue(t){return{kind:"validation",type:"ipv4",reference:Ue,async:!1,expects:null,requirement:F,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"IPv4",n,e),n}}}function Ge(t){return{kind:"validation",type:"ipv6",reference:Ge,async:!1,expects:null,requirement:U,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"IPv6",n,e),n}}}function Xe(t){return{kind:"validation",type:"iso_date",reference:Xe,async:!1,expects:null,requirement:X,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"date",n,e),n}}}function He(t){return{kind:"validation",type:"iso_date_time",reference:He,async:!1,expects:null,requirement:H,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"date-time",n,e),n}}}function Je(t){return{kind:"validation",type:"iso_time",reference:Je,async:!1,expects:null,requirement:J,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"time",n,e),n}}}function Ze(t){return{kind:"validation",type:"iso_time_second",reference:Ze,async:!1,expects:null,requirement:Z,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"time-second",n,e),n}}}function Qe(t){return{kind:"validation",type:"iso_timestamp",reference:Qe,async:!1,expects:null,requirement:Q,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"timestamp",n,e),n}}}function Ye(t){return{kind:"validation",type:"iso_week",reference:Ye,async:!1,expects:null,requirement:Y,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"week",n,e),n}}}function en(t,n){return{kind:"validation",type:"length",reference:en,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length!==this.requirement&&r(this,"length",e,s,{received:`${e.value.length}`}),e}}}function nn(t){return{kind:"validation",type:"mac",reference:nn,async:!1,expects:null,requirement:te,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"MAC",n,e),n}}}function tn(t){return{kind:"validation",type:"mac48",reference:tn,async:!1,expects:null,requirement:ee,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"48-bit MAC",n,e),n}}}function sn(t){return{kind:"validation",type:"mac64",reference:sn,async:!1,expects:null,requirement:ne,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"64-bit MAC",n,e),n}}}function un(t){return{kind:"transformation",type:"map_items",reference:un,async:!1,operation:t,_run(n){return n.value=n.value.map(this.operation),n}}}function rn(t,n){return{kind:"validation",type:"max_bytes",reference:rn,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let u=new TextEncoder().encode(e.value).length;u>this.requirement&&r(this,"bytes",e,s,{received:`${u}`})}return e}}}function In(t,n){return{kind:"validation",type:"max_length",reference:In,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length>this.requirement&&r(this,"length",e,s,{received:`${e.value.length}`}),e}}}function on(t,n){return{kind:"validation",type:"max_size",reference:on,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size>this.requirement&&r(this,"size",e,s,{received:`${e.value.size}`}),e}}}function an(t,n){return{kind:"validation",type:"max_value",reference:an,async:!1,expects:`<=${t instanceof Date?t.toJSON():f(t)}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value>this.requirement&&r(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function mn(t,n){return{kind:"validation",type:"mime_type",reference:mn,async:!1,expects:d(t.map(e=>`"${e}"`),"|"),requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement.includes(e.value.type)&&r(this,"MIME type",e,s,{received:`"${e.value.type}"`}),e}}}function pn(t,n){return{kind:"validation",type:"min_bytes",reference:pn,async:!1,expects:`>=${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let u=new TextEncoder().encode(e.value).length;u=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size=${t instanceof Date?t.toJSON():f(t)}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value=e.value&&r(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function wn(t){return{kind:"validation",type:"octal",reference:wn,async:!1,expects:null,requirement:se,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&r(this,"octal",n,e),n}}}function M(t,n){if(t.issues)for(let e of n)for(let s of t.issues){let u=!1,o=Math.min(e.length,s.path?.length??0);for(let i=0;ir(this,s?.label??"input",n,e,s)}),n}}}function An(t){return{kind:"validation",type:"raw_check",reference:An,async:!0,expects:null,async _run(n,e){return await t({dataset:n,config:e,addIssue:s=>r(this,s?.label??"input",n,e,s)}),n}}}function bn(t){return{kind:"transformation",type:"raw_transform",reference:bn,async:!1,_run(n,e){let s=t({dataset:n,config:e,addIssue:u=>r(this,u?.label??"input",n,e,u),NEVER:null});return n.issues?n.typed=!1:n.value=s,n}}}function En(t){return{kind:"transformation",type:"raw_transform",reference:En,async:!0,async _run(n,e){let s=await t({dataset:n,config:e,addIssue:u=>r(this,u?.label??"input",n,e,u),NEVER:null});return n.issues?n.typed=!1:n.value=s,n}}}function Mn(){return{kind:"transformation",type:"readonly",reference:Mn,async:!1,_run(t){return t}}}function Pn(t,n){return{kind:"transformation",type:"reduce_items",reference:Pn,async:!1,operation:t,initial:n,_run(e){return e.value=e.value.reduce(this.operation,this.initial),e}}}function jn(t,n){return{kind:"validation",type:"regex",reference:jn,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement.test(e.value)&&r(this,"format",e,s),e}}}function Rn(t){return{kind:"validation",type:"safe_integer",reference:Rn,async:!1,expects:null,requirement:Number.isSafeInteger,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&r(this,"safe integer",n,e),n}}}function vn(t,n){return{kind:"validation",type:"size",reference:vn,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size!==this.requirement&&r(this,"size",e,s,{received:`${e.value.size}`}),e}}}function _n(t,n){return{kind:"validation",type:"some_item",reference:_n,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.some(this.requirement)&&r(this,"item",e,s),e}}}function qn(t){return{kind:"transformation",type:"sort_items",reference:qn,async:!1,operation:t,_run(n){return n.value=n.value.sort(this.operation),n}}}function Dn(t,n){return{kind:"validation",type:"starts_with",reference:Dn,async:!1,expects:`"${t}"`,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.startsWith(this.requirement)&&r(this,"start",e,s,{received:`"${e.value.slice(0,this.requirement.length)}"`}),e}}}function Nn(){return{kind:"transformation",type:"to_lower_case",reference:Nn,async:!1,_run(t){return t.value=t.value.toLowerCase(),t}}}function Wn(t){return{kind:"transformation",type:"to_max_value",reference:Wn,async:!1,requirement:t,_run(n){return n.value=n.value>this.requirement?this.requirement:n.value,n}}}function Vn(t){return{kind:"transformation",type:"to_min_value",reference:Vn,async:!1,requirement:t,_run(n){return n.value=n.value=e.value)&&r(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function bs(t,n){return{...t,_run(e,s){return t._run(e,{...s,...n})}}}function x(t,n,e){return typeof t.fallback=="function"?t.fallback(n,e):t.fallback}function Es(t,n){return{...t,fallback:n,_run(e,s){let u=t._run(e,s);return u.issues?{typed:!0,value:x(this,u,s)}:u}}}function Ms(t,n){return{...t,fallback:n,async:!0,async _run(e,s){let u=await t._run(e,s);return u.issues?{typed:!0,value:await x(this,u,s)}:u}}}function Ps(t){let n={};for(let e of t)if(e.path){let s=ae(e);s?(n.nested||(n.nested={}),n.nested[s]?n.nested[s].push(e.message):n.nested[s]=[e.message]):n.other?n.other.push(e.message):n.other=[e.message]}else n.root?n.root.push(e.message):n.root=[e.message];return n}function js(t,n){return{...t,_run(e,s){let u=e.issues&&[...e.issues];if(t._run(e,s),e.issues){for(let o of e.issues)if(!u?.includes(o)){let i=e.value;for(let a of n){let I=i[a],m={type:"unknown",origin:"value",input:i,key:a,value:I};if(o.path?o.path.push(m):o.path=[m],!I)break;i=I}}}return e}}}function Rs(t,n){return{...t,async:!0,async _run(e,s){let u=e.issues&&[...e.issues];if(await t._run(e,s),e.issues){for(let o of e.issues)if(!u?.includes(o)){let i=e.value;for(let a of n){let I=i[a],m={type:"unknown",origin:"value",input:i,key:a,value:I};if(o.path?o.path.push(m):o.path=[m],!I)break;i=I}}}return e}}}function y(t,n,e){return typeof t.default=="function"?t.default(n,e):t.default}function me(t){if("entries"in t){let n={};for(let e in t.entries)n[e]=me(t.entries[e]);return n}return"items"in t?t.items.map(me):y(t)}async function pe(t){return"entries"in t?Object.fromEntries(await Promise.all(Object.entries(t.entries).map(async([n,e])=>[n,await pe(e)]))):"items"in t?Promise.all(t.items.map(pe)):y(t)}function ce(t){if("entries"in t){let n={};for(let e in t.entries)n[e]=ce(t.entries[e]);return n}return"items"in t?t.items.map(ce):x(t)}async function Te(t){return"entries"in t?Object.fromEntries(await Promise.all(Object.entries(t.entries).map(async([n,e])=>[n,await Te(e)]))):"items"in t?Promise.all(t.items.map(Te)):x(t)}function vs(t,n){return!t._run({typed:!1,value:n},{abortEarly:!0}).issues}function Jn(){return{kind:"schema",type:"any",reference:Jn,expects:"any",async:!1,_run(t){return t.typed=!0,t}}}function Zn(t,n){return{kind:"schema",type:"array",reference:Zn,expects:"Array",async:!1,item:t,message:n,_run(e,s){let u=e.value;if(Array.isArray(u)){e.typed=!0,e.value=[];for(let o=0;othis.item._run({typed:!1,value:i},s)));for(let i=0;iisNaN(+s)).map(([,s])=>s);return{kind:"schema",type:"enum",reference:rt,expects:d(e.map(f),"|"),async:!1,enum:t,options:e,message:n,_run(s,u){return this.options.includes(s.value)?s.typed=!0:r(this,"type",s,u),s}}}function It(t){return{kind:"schema",type:"file",reference:It,expects:"File",async:!1,message:t,_run(n,e){return n.value instanceof File?n.typed=!0:r(this,"type",n,e),n}}}function ot(t){return{kind:"schema",type:"function",reference:ot,expects:"Function",async:!1,message:t,_run(n,e){return typeof n.value=="function"?n.typed=!0:r(this,"type",n,e),n}}}function it(t,n){return{kind:"schema",type:"instance",reference:it,expects:t.name,async:!1,class:t,message:n,_run(e,s){return e.value instanceof this.class?e.typed=!0:r(this,"type",e,s),e}}}function g(t,n){if(typeof t==typeof n){if(t===n||t instanceof Date&&n instanceof Date&&+t==+n)return{value:t};if(t&&n&&t.constructor===Object&&n.constructor===Object){for(let e in n)if(e in t){let s=g(t[e],n[e]);if(s.issue)return s;t[e]=s.value}else t[e]=n[e];return{value:t}}if(Array.isArray(t)&&Array.isArray(n)&&t.length===n.length){for(let e=0;ee.expects),"&"),async:!1,options:t,message:n,_run(e,s){if(this.options.length){let u=e.value,o;e.typed=!0;for(let i of this.options){let a=i._run({typed:!1,value:u},s);if(a.issues&&(e.issues?e.issues.push(...a.issues):e.issues=a.issues,s.abortEarly)){e.typed=!1;break}a.typed||(e.typed=!1),e.typed&&(o?o.push(a.value):o=[a.value])}if(e.typed){e.value=o[0];for(let i=1;ie.expects),"&"),async:!0,options:t,message:n,async _run(e,s){if(this.options.length){let u=e.value,o;e.typed=!0;let i=await Promise.all(this.options.map(a=>a._run({typed:!1,value:u},s)));for(let a of i){if(a.issues&&(e.issues?e.issues.push(...a.issues):e.issues=a.issues,s.abortEarly)){e.typed=!1;break}a.typed||(e.typed=!1),e.typed&&(o?o.push(a.value):o=[a.value])}if(e.typed){e.value=o[0];for(let a=1;a{let I=u[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in u)&&(e.value[i]=I.value)}if(!e.issues||!s.abortEarly)for(let i in u)l(u,i)&&!(i in this.entries)&&(e.value[i]=u[i])}else r(this,"type",e,s);return e}}}function yt(t,n){return{kind:"schema",type:"loose_tuple",reference:yt,expects:"Array",async:!1,items:t,message:n,_run(e,s){let u=e.value;if(Array.isArray(u)){e.typed=!0,e.value=[];for(let o=0;o{let I=u[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}if(!e.issues||!s.abortEarly)for(let i=this.items.length;iPromise.all([a,I,this.key._run({typed:!1,value:a},u),this.value._run({typed:!1,value:I},u)])));for(let[a,I,m,p]of i){if(m.issues){let c={type:"map",origin:"key",input:o,key:a,value:I};for(let T of m.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=m.issues),u.abortEarly){s.typed=!1;break}}if(p.issues){let c={type:"map",origin:"value",input:o,key:a,value:I};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}(!m.typed||!p.typed)&&(s.typed=!1),s.value.set(m.value,p.value)}}else r(this,"type",s,u);return s}}}function xt(t){return{kind:"schema",type:"nan",reference:xt,expects:"NaN",async:!1,message:t,_run(n,e){return Number.isNaN(n.value)?n.typed=!0:r(this,"type",n,e),n}}}function Ot(t){return{kind:"schema",type:"never",reference:Ot,expects:"never",async:!1,message:t,_run(n,e){return r(this,"type",n,e),n}}}function wt(t,n){return{kind:"schema",type:"non_nullable",reference:wt,expects:"!null",async:!1,wrapped:t,message:n,_run(e,s){return e.value===null?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function gt(t,n){return{kind:"schema",type:"non_nullable",reference:gt,expects:"!null",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===null?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function St(t,n){return{kind:"schema",type:"non_nullish",reference:St,expects:"(!null & !undefined)",async:!1,wrapped:t,message:n,_run(e,s){return e.value===null||e.value===void 0?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function Bt(t,n){return{kind:"schema",type:"non_nullish",reference:Bt,expects:"(!null & !undefined)",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===null||e.value===void 0?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function P(t,n){return{kind:"schema",type:"non_optional",reference:P,expects:"!undefined",async:!1,wrapped:t,message:n,_run(e,s){return e.value===void 0?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function j(t,n){return{kind:"schema",type:"non_optional",reference:j,expects:"!undefined",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===void 0?(r(this,"type",e,s),e):this.wrapped._run(e,s)}}}function At(t){return{kind:"schema",type:"null",reference:At,expects:"null",async:!1,message:t,_run(n,e){return n.value===null?n.typed=!0:r(this,"type",n,e),n}}}function bt(t,...n){let e={kind:"schema",type:"nullable",reference:bt,expects:`(${t.expects} | null)`,async:!1,wrapped:t,_run(s,u){return s.value===null&&("default"in this&&(s.value=y(this,s,u)),s.value===null)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function Et(t,...n){let e={kind:"schema",type:"nullable",reference:Et,expects:`(${t.expects} | null)`,async:!0,wrapped:t,async _run(s,u){return s.value===null&&("default"in this&&(s.value=await y(this,s,u)),s.value===null)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function Mt(t,...n){let e={kind:"schema",type:"nullish",reference:Mt,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,_run(s,u){return(s.value===null||s.value===void 0)&&("default"in this&&(s.value=y(this,s,u)),s.value===null||s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function Pt(t,...n){let e={kind:"schema",type:"nullish",reference:Pt,expects:`(${t.expects} | null | undefined)`,async:!0,wrapped:t,async _run(s,u){return(s.value===null||s.value===void 0)&&("default"in this&&(s.value=await y(this,s,u)),s.value===null||s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function jt(t){return{kind:"schema",type:"number",reference:jt,expects:"number",async:!1,message:t,_run(n,e){return typeof n.value=="number"&&!isNaN(n.value)?n.typed=!0:r(this,"type",n,e),n}}}function Rt(t,n){return{kind:"schema",type:"object",reference:Rt,expects:"Object",async:!1,entries:t,message:n,_run(e,s){let u=e.value;if(u&&typeof u=="object"){e.typed=!0,e.value={};for(let o in this.entries){let i=u[o],a=this.entries[o]._run({typed:!1,value:i},s);if(a.issues){let I={type:"object",origin:"value",input:u,key:o,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||o in u)&&(e.value[o]=a.value)}}else r(this,"type",e,s);return e}}}function vt(t,n){return{kind:"schema",type:"object",reference:vt,expects:"Object",async:!0,entries:t,message:n,async _run(e,s){let u=e.value;if(u&&typeof u=="object"){e.typed=!0,e.value={};let o=await Promise.all(Object.entries(this.entries).map(async([i,a])=>{let I=u[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in u)&&(e.value[i]=I.value)}}else r(this,"type",e,s);return e}}}function _t(t,n,e){return{kind:"schema",type:"object_with_rest",reference:_t,expects:"Object",async:!1,entries:t,rest:n,message:e,_run(s,u){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};for(let i in this.entries){let a=o[i],I=this.entries[i]._run({typed:!1,value:a},u);if(I.issues){let m={type:"object",origin:"value",input:o,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],s.issues?.push(p);if(s.issues||(s.issues=I.issues),u.abortEarly){s.typed=!1;break}}I.typed||(s.typed=!1),(I.value!==void 0||i in o)&&(s.value[i]=I.value)}if(!s.issues||!u.abortEarly){for(let i in o)if(l(o,i)&&!(i in this.entries)){let a=o[i],I=this.rest._run({typed:!1,value:a},u);if(I.issues){let m={type:"object",origin:"value",input:o,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],s.issues?.push(p);if(s.issues||(s.issues=I.issues),u.abortEarly){s.typed=!1;break}}I.typed||(s.typed=!1),s.value[i]=I.value}}}else r(this,"type",s,u);return s}}}function qt(t,n,e){return{kind:"schema",type:"object_with_rest",reference:qt,expects:"Object",async:!0,entries:t,rest:n,message:e,async _run(s,u){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};let[i,a]=await Promise.all([Promise.all(Object.entries(this.entries).map(async([I,m])=>{let p=o[I];return[I,p,await m._run({typed:!1,value:p},u)]})),Promise.all(Object.entries(o).filter(([I])=>l(o,I)&&!(I in this.entries)).map(async([I,m])=>[I,m,await this.rest._run({typed:!1,value:m},u)]))]);for(let[I,m,p]of i){if(p.issues){let c={type:"object",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),(p.value!==void 0||I in o)&&(s.value[I]=p.value)}if(!s.issues||!u.abortEarly)for(let[I,m,p]of a){if(p.issues){let c={type:"object",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value[I]=p.value}}else r(this,"type",s,u);return s}}}function R(t,...n){let e={kind:"schema",type:"optional",reference:R,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,_run(s,u){return s.value===void 0&&("default"in this&&(s.value=y(this,s,u)),s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function v(t,...n){let e={kind:"schema",type:"optional",reference:v,expects:`(${t.expects} | undefined)`,async:!0,wrapped:t,async _run(s,u){return s.value===void 0&&("default"in this&&(s.value=await y(this,s,u)),s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,u)}};return 0 in n&&(e.default=n[0]),e}function _(t,n){return{kind:"schema",type:"picklist",reference:_,expects:d(t.map(f),"|"),async:!1,options:t,message:n,_run(e,s){return this.options.includes(e.value)?e.typed=!0:r(this,"type",e,s),e}}}function Dt(t){return{kind:"schema",type:"promise",reference:Dt,expects:"Promise",async:!1,message:t,_run(n,e){return n.value instanceof Promise?n.typed=!0:r(this,"type",n,e),n}}}function Nt(t,n,e){return{kind:"schema",type:"record",reference:Nt,expects:"Object",async:!1,key:t,value:n,message:e,_run(s,u){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};for(let i in o)if(l(o,i)){let a=o[i],I=this.key._run({typed:!1,value:i},u);if(I.issues){let p={type:"object",origin:"key",input:o,key:i,value:a};for(let c of I.issues)c.path=[p],s.issues?.push(c);if(s.issues||(s.issues=I.issues),u.abortEarly){s.typed=!1;break}}let m=this.value._run({typed:!1,value:a},u);if(m.issues){let p={type:"object",origin:"value",input:o,key:i,value:a};for(let c of m.issues)c.path?c.path.unshift(p):c.path=[p],s.issues?.push(c);if(s.issues||(s.issues=m.issues),u.abortEarly){s.typed=!1;break}}(!I.typed||!m.typed)&&(s.typed=!1),I.typed&&(s.value[I.value]=m.value)}}else r(this,"type",s,u);return s}}}function Wt(t,n,e){return{kind:"schema",type:"record",reference:Wt,expects:"Object",async:!0,key:t,value:n,message:e,async _run(s,u){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};let i=await Promise.all(Object.entries(o).filter(([a])=>l(o,a)).map(([a,I])=>Promise.all([a,I,this.key._run({typed:!1,value:a},u),this.value._run({typed:!1,value:I},u)])));for(let[a,I,m,p]of i){if(m.issues){let c={type:"object",origin:"key",input:o,key:a,value:I};for(let T of m.issues)T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=m.issues),u.abortEarly){s.typed=!1;break}}if(p.issues){let c={type:"object",origin:"value",input:o,key:a,value:I};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}(!m.typed||!p.typed)&&(s.typed=!1),m.typed&&(s.value[m.value]=p.value)}}else r(this,"type",s,u);return s}}}function Vt(t,n){return{kind:"schema",type:"set",reference:Vt,expects:"Set",async:!1,value:t,message:n,_run(e,s){let u=e.value;if(u instanceof Set){e.typed=!0,e.value=new Set;for(let o of u){let i=this.value._run({typed:!1,value:o},s);if(i.issues){let a={type:"set",origin:"value",input:u,key:null,value:o};for(let I of i.issues)I.path?I.path.unshift(a):I.path=[a],e.issues?.push(I);if(e.issues||(e.issues=i.issues),s.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.add(i.value)}}else r(this,"type",e,s);return e}}}function Ct(t,n){return{kind:"schema",type:"set",reference:Ct,expects:"Set",async:!0,value:t,message:n,async _run(e,s){let u=e.value;if(u instanceof Set){e.typed=!0,e.value=new Set;let o=await Promise.all([...u].map(async i=>[i,await this.value._run({typed:!1,value:i},s)]));for(let[i,a]of o){if(a.issues){let I={type:"set",origin:"value",input:u,key:null,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.add(a.value)}}else r(this,"type",e,s);return e}}}function Lt(t,n){return{kind:"schema",type:"strict_object",reference:Lt,expects:"Object",async:!1,entries:t,message:n,_run(e,s){let u=e.value;if(u&&typeof u=="object"){e.typed=!0,e.value={};for(let o in this.entries){let i=u[o],a=this.entries[o]._run({typed:!1,value:i},s);if(a.issues){let I={type:"object",origin:"value",input:u,key:o,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||o in u)&&(e.value[o]=a.value)}if(!e.issues||!s.abortEarly){for(let o in u)if(!(o in this.entries)){let i=u[o];r(this,"type",e,s,{input:i,expected:"never",path:[{type:"object",origin:"value",input:u,key:o,value:i}]});break}}}else r(this,"type",e,s);return e}}}function Kt(t,n){return{kind:"schema",type:"strict_object",reference:Kt,expects:"Object",async:!0,entries:t,message:n,async _run(e,s){let u=e.value;if(u&&typeof u=="object"){e.typed=!0,e.value={};let o=await Promise.all(Object.entries(this.entries).map(async([i,a])=>{let I=u[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in u)&&(e.value[i]=I.value)}if(!e.issues||!s.abortEarly){for(let i in u)if(!(i in this.entries)){let a=u[i];r(this,"type",e,s,{input:a,expected:"never",path:[{type:"object",origin:"value",input:u,key:i,value:a}]});break}}}else r(this,"type",e,s);return e}}}function $t(t,n){return{kind:"schema",type:"strict_tuple",reference:$t,expects:"Array",async:!1,items:t,message:n,_run(e,s){let u=e.value;if(Array.isArray(u)){e.typed=!0,e.value=[];for(let o=0;o{let I=u[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}if(!(e.issues&&s.abortEarly)&&this.items.length{let I=u[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:u,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}}else r(this,"type",e,s);return e}}}function Ht(t,n,e){return{kind:"schema",type:"tuple_with_rest",reference:Ht,expects:"Array",async:!1,items:t,rest:n,message:e,_run(s,u){let o=s.value;if(Array.isArray(o)){s.typed=!0,s.value=[];for(let i=0;i{let p=o[m];return[m,p,await I._run({typed:!1,value:p},u)]})),Promise.all(o.slice(this.items.length).map(async(I,m)=>[m+this.items.length,I,await this.rest._run({typed:!1,value:I},u)]))]);for(let[I,m,p]of i){if(p.issues){let c={type:"array",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value.push(p.value)}if(!s.issues||!u.abortEarly)for(let[I,m,p]of a){if(p.issues){let c={type:"array",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),u.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value.push(p.value)}}else r(this,"type",s,u);return s}}}function Zt(t){return{kind:"schema",type:"undefined",reference:Zt,expects:"undefined",async:!1,message:t,_run(n,e){return n.value===void 0?n.typed=!0:r(this,"type",n,e),n}}}function S(t){let n;if(t)for(let e of t)n?n.push(...e.issues):n=e.issues;return n}function Qt(t,n){return{kind:"schema",type:"union",reference:Qt,expects:d(t.map(e=>e.expects),"|"),async:!1,options:t,message:n,_run(e,s){let u,o,i;for(let a of this.options){let I=a._run({typed:!1,value:e.value},s);if(I.typed)if(I.issues)o?o.push(I):o=[I];else{u=I;break}else i?i.push(I):i=[I]}if(u)return u;if(o){if(o.length===1)return o[0];r(this,"type",e,s,{issues:S(o)}),e.typed=!0}else{if(i?.length===1)return i[0];r(this,"type",e,s,{issues:S(i)})}return e}}}function Yt(t,n){return{kind:"schema",type:"union",reference:Yt,expects:d(t.map(e=>e.expects),"|"),async:!0,options:t,message:n,async _run(e,s){let u,o,i;for(let a of this.options){let I=await a._run({typed:!1,value:e.value},s);if(I.typed)if(I.issues)o?o.push(I):o=[I];else{u=I;break}else i?i.push(I):i=[I]}if(u)return u;if(o){if(o.length===1)return o[0];r(this,"type",e,s,{issues:S(o)}),e.typed=!0}else{if(i?.length===1)return i[0];r(this,"type",e,s,{issues:S(i)})}return e}}}function es(){return{kind:"schema",type:"unknown",reference:es,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function E(t,n,e=[]){for(let s of n)s.type==="variant"?E(t,s.options,e):e.push(s.entries[t].expects);return e}function ns(t,n,e){let s;return{kind:"schema",type:"variant",reference:ns,expects:"Object",async:!1,key:t,options:n,message:e,_run(u,o){let i=u.value;if(i&&typeof i=="object"){let a=i[this.key];if(this.key in i){let I;for(let m of this.options)if(m.type==="variant"||!m.entries[this.key]._run({typed:!1,value:a},o).issues){let p=m._run({typed:!1,value:i},o);if(!p.issues)return p;(!I||!I.typed&&p.typed)&&(I=p)}if(I)return I}s||(s=d(E(this.key,this.options),"|")),r(this,"type",u,o,{input:a,expected:s,path:[{type:"object",origin:"value",input:i,key:this.key,value:a}]})}else r(this,"type",u,o);return u}}}function ts(t,n,e){let s;return{kind:"schema",type:"variant",reference:ts,expects:"Object",async:!0,key:t,options:n,message:e,async _run(u,o){let i=u.value;if(i&&typeof i=="object"){let a=i[this.key];if(this.key in i){let I;for(let m of this.options)if(m.type==="variant"||!(await m.entries[this.key]._run({typed:!1,value:a},o)).issues){let p=await m._run({typed:!1,value:i},o);if(!p.issues)return p;(!I||!I.typed&&p.typed)&&(I=p)}if(I)return I}s||(s=d(E(this.key,this.options),"|")),r(this,"type",u,o,{input:a,expected:s,path:[{type:"object",origin:"value",input:i,key:this.key,value:a}]})}else r(this,"type",u,o);return u}}}function ss(t){return{kind:"schema",type:"void",reference:ss,expects:"void",async:!1,message:t,_run(n,e){return n.value===void 0?n.typed=!0:r(this,"type",n,e),n}}}function _s(t,n){return _(Object.keys(t.entries),n)}function qs(t,n){let e={...t.entries};for(let s of n)delete e[s];return{...t,entries:e}}function fe(t,n,e){let s=t._run({typed:!1,value:n},k(e));if(s.issues)throw new h(s.issues);return s.value}async function de(t,n,e){let s=await t._run({typed:!1,value:n},k(e));if(s.issues)throw new h(s.issues);return s.value}function Ds(t,n){let e=s=>fe(t,s,n);return e.schema=t,e.config=n,e}function Ns(t,n){let e=s=>de(t,s,n);return e.schema=t,e.config=n,e}function Ws(t,n){let e={};for(let s in t.entries)e[s]=!n||n.includes(s)?R(t.entries[s]):t.entries[s];return{...t,entries:e}}function Vs(t,n){let e={};for(let s in t.entries)e[s]=!n||n.includes(s)?v(t.entries[s]):t.entries[s];return{...t,entries:e}}function Cs(t,n){let e={};for(let s of n)e[s]=t.entries[s];return{...t,entries:e}}function Ls(...t){return{...t[0],pipe:t,_run(n,e){for(let s of t)if(s.kind!=="metadata"){if(n.issues&&(s.kind==="schema"||s.kind==="transformation")){n.typed=!1;break}(!n.issues||!e.abortEarly&&!e.abortPipeEarly)&&(n=s._run(n,e))}return n}}}function Ks(...t){return{...t[0],pipe:t,async:!0,async _run(n,e){for(let s of t)if(s.kind!=="metadata"){if(n.issues&&(s.kind==="schema"||s.kind==="transformation")){n.typed=!1;break}(!n.issues||!e.abortEarly&&!e.abortPipeEarly)&&(n=await s._run(n,e))}return n}}}function $s(t,n,e){let s=Array.isArray(n)?n:void 0,u=Array.isArray(n)?e:n,o={};for(let i in t.entries)o[i]=!s||s.includes(i)?P(t.entries[i],u):t.entries[i];return{...t,entries:o}}function zs(t,n,e){let s=Array.isArray(n)?n:void 0,u=Array.isArray(n)?e:n,o={};for(let i in t.entries)o[i]=!s||s.includes(i)?j(t.entries[i],u):t.entries[i];return{...t,entries:o}}function ye(t,n,e){let s=t._run({typed:!1,value:n},k(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}async function le(t,n,e){let s=await t._run({typed:!1,value:n},k(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}function Fs(t,n){let e=s=>ye(t,s,n);return e.schema=t,e.config=n,e}function Us(t,n){let e=s=>le(t,s,n);return e.schema=t,e.config=n,e}function Gs(t){return t.wrapped}0&&(module.exports={BASE64_REGEX,BIC_REGEX,CUID2_REGEX,DECIMAL_REGEX,EMAIL_REGEX,EMOJI_REGEX,HEXADECIMAL_REGEX,HEX_COLOR_REGEX,IMEI_REGEX,IPV4_REGEX,IPV6_REGEX,IP_REGEX,ISO_DATE_REGEX,ISO_DATE_TIME_REGEX,ISO_TIMESTAMP_REGEX,ISO_TIME_REGEX,ISO_TIME_SECOND_REGEX,ISO_WEEK_REGEX,MAC48_REGEX,MAC64_REGEX,MAC_REGEX,OCTAL_REGEX,ULID_REGEX,UUID_REGEX,ValiError,_addIssue,_isLuhnAlgo,_isValidObjectKey,_joinExpects,_stringify,any,array,arrayAsync,awaitAsync,base64,bic,bigint,blob,boolean,brand,bytes,check,checkAsync,checkItems,config,creditCard,cuid2,custom,customAsync,date,decimal,deleteGlobalConfig,deleteGlobalMessage,deleteSchemaMessage,deleteSpecificMessage,description,email,emoji,empty,endsWith,entriesFromList,enum:null,enum_,everyItem,excludes,fallback,fallbackAsync,file,filterItems,findItem,finite,flatten,forward,forwardAsync,function:null,function_,getDefault,getDefaults,getDefaultsAsync,getDotPath,getFallback,getFallbacks,getFallbacksAsync,getGlobalConfig,getGlobalMessage,getSchemaMessage,getSpecificMessage,hash,hexColor,hexadecimal,imei,includes,instance,integer,intersect,intersectAsync,ip,ipv4,ipv6,is,isOfKind,isOfType,isValiError,isoDate,isoDateTime,isoTime,isoTimeSecond,isoTimestamp,isoWeek,keyof,lazy,lazyAsync,length,literal,looseObject,looseObjectAsync,looseTuple,looseTupleAsync,mac,mac48,mac64,map,mapAsync,mapItems,maxBytes,maxLength,maxSize,maxValue,mimeType,minBytes,minLength,minSize,minValue,multipleOf,nan,never,nonEmpty,nonNullable,nonNullableAsync,nonNullish,nonNullishAsync,nonOptional,nonOptionalAsync,normalize,notBytes,notLength,notSize,notValue,null:null,null_,nullable,nullableAsync,nullish,nullishAsync,number,object,objectAsync,objectWithRest,objectWithRestAsync,octal,omit,optional,optionalAsync,parse,parseAsync,parser,parserAsync,partial,partialAsync,partialCheck,partialCheckAsync,pick,picklist,pipe,pipeAsync,promise,rawCheck,rawCheckAsync,rawTransform,rawTransformAsync,readonly,record,recordAsync,reduceItems,regex,required,requiredAsync,safeInteger,safeParse,safeParseAsync,safeParser,safeParserAsync,set,setAsync,setGlobalConfig,setGlobalMessage,setSchemaMessage,setSpecificMessage,size,someItem,sortItems,startsWith,strictObject,strictObjectAsync,strictTuple,strictTupleAsync,string,symbol,toLowerCase,toMaxValue,toMinValue,toUpperCase,transform,transformAsync,trim,trimEnd,trimStart,tuple,tupleAsync,tupleWithRest,tupleWithRestAsync,ulid,undefined,undefined_,union,unionAsync,unknown,unwrap,url,uuid,value,variant,variantAsync,void:null,void_}); diff --git a/src/libMPC/node_modules/valibot/dist/index.min.js b/src/libMPC/node_modules/valibot/dist/index.min.js new file mode 100644 index 0000000..0ed4fcc --- /dev/null +++ b/src/libMPC/node_modules/valibot/dist/index.min.js @@ -0,0 +1 @@ +function le(){return{kind:"transformation",type:"await",reference:le,async:!0,async _run(t){return t.value=await t.value,t}}}var q=/^(?:[\da-z+/]{4})*(?:[\da-z+/]{2}==|[\da-z+/]{3}=)?$/iu,D=/^[A-Z]{6}(?!00)[\dA-Z]{2}(?:[\dA-Z]{3})?$/u,N=/^[a-z][\da-z]*$/u,W=/^\d+$/u,V=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,C=/^(?:[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}))*)+$/u,L=/^(?:0[hx])?[\da-f]+$/iu,K=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/iu,$=/^\d{15}$|^\d{2}-\d{6}-\d{6}-\d$/u,z=/^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$/u,F=/^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu,U=/^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$|^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|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]{2}-){7}[\da-f]{2}$|^(?:[\da-f]{4}\.){3}[\da-f]{4}$|^(?:[\da-f]{4}:){3}[\da-f]{4}$/iu,te=/^(?:0o)?[0-7]+$/iu,se=/^[\da-hjkmnp-tv-z]{26}$/iu,ue=/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu;var w;function ms(t){w={...w,...t}}function k(t){return{lang:t?.lang??w?.lang,message:t?.message,abortEarly:t?.abortEarly??w?.abortEarly,abortPipeEarly:t?.abortPipeEarly??w?.abortPipeEarly}}function ps(){w=void 0}var B;function Ts(t,n){B||(B=new Map),B.set(n,t)}function re(t){return B?.get(t)}function fs(t){B?.delete(t)}var A;function ys(t,n){A||(A=new Map),A.set(n,t)}function Ie(t){return A?.get(t)}function ls(t){A?.delete(t)}var O;function hs(t,n,e){O||(O=new Map),O.get(t)||O.set(t,new Map),O.get(t).set(e,n)}function oe(t,n){return O?.get(t)?.get(n)}function xs(t,n){O?.get(t)?.delete(n)}function f(t){let n=typeof t;return n==="string"?`"${t}"`:n==="number"||n==="bigint"||n==="boolean"?`${t}`:n==="object"||n==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":n}function u(t,n,e,s,r){let o=r&&"input"in r?r.input:e.value,i=r?.expected??t.expects??null,a=r?.received??f(o),I={kind:t.kind,type:t.type,input:o,expected:i,received:a,message:`Invalid ${n}: ${i?`Expected ${i} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:r?.path,issues:r?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},m=t.kind==="schema",p=r?.message??t.message??oe(t.reference,I.lang)??(m?Ie(I.lang):null)??s.message??re(I.lang);p&&(I.message=typeof p=="function"?p(I):p),m&&(e.typed=!1),e.issues?e.issues.push(I):e.issues=[I]}var ke=/\D/gu;function E(t){let n=t.replace(ke,""),e=n.length,s=1,r=0;for(;e;){let o=+n[--e];s^=1,r+=s?[0,2,4,6,8,1,3,5,7,9][o]:o}return r%10===0}function l(t,n){return Object.hasOwn(t,n)&&n!=="__proto__"&&n!=="prototype"&&n!=="constructor"}function d(t,n){let e=[...new Set(t)];return e.length>1?`(${e.join(` ${n} `)})`:e[0]??"never"}function Ms(t,n){let e={};for(let s of t)e[s]=n;return e}function ie(t){if(t.path){let n="";for(let e of t.path)if(typeof e.key=="string"||typeof e.key=="number")n?n+=`.${e.key}`:n+=e.key;else return null;return n}return null}function Rs(t,n){return n.kind===t}function _s(t,n){return n.type===t}function Ns(t){return t instanceof h}var h=class extends Error{issues;constructor(n){super(n[0].message),this.name="ValiError",this.issues=n}};function he(t){return{kind:"validation",type:"base64",reference:he,async:!1,expects:null,requirement:q,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"Base64",n,e),n}}}function xe(t){return{kind:"validation",type:"bic",reference:xe,async:!1,expects:null,requirement:D,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"BIC",n,e),n}}}function Oe(t){return{kind:"transformation",type:"brand",reference:Oe,async:!1,name:t,_run(n){return n}}}function we(t,n){return{kind:"validation",type:"bytes",reference:we,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let r=new TextEncoder().encode(e.value).length;r!==this.requirement&&u(this,"bytes",e,s,{received:`${r}`})}return e}}}function ge(t,n){return{kind:"validation",type:"check",reference:ge,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement(e.value)&&u(this,"input",e,s),e}}}function Se(t,n){return{kind:"validation",type:"check",reference:Se,async:!0,expects:null,requirement:t,message:n,async _run(e,s){return e.typed&&!await this.requirement(e.value)&&u(this,"input",e,s),e}}}function Be(t,n){return{kind:"validation",type:"check_items",reference:Be,async:!1,expects:null,requirement:t,message:n,_run(e,s){if(e.typed)for(let r=0;rs.test(e))&&E(e)},message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&u(this,"credit card",n,e),n}}}function Pe(t){return{kind:"validation",type:"cuid2",reference:Pe,async:!1,expects:null,requirement:N,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"Cuid2",n,e),n}}}function je(t){return{kind:"validation",type:"decimal",reference:je,async:!1,expects:null,requirement:W,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"decimal",n,e),n}}}function Re(t){return{kind:"metadata",type:"description",reference:Re,description:t}}function ve(t){return{kind:"validation",type:"email",reference:ve,expects:null,async:!1,requirement:V,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"email",n,e),n}}}function _e(t){return{kind:"validation",type:"emoji",reference:_e,async:!1,expects:null,requirement:C,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"emoji",n,e),n}}}function qe(t){return{kind:"validation",type:"empty",reference:qe,async:!1,expects:"0",message:t,_run(n,e){return n.typed&&n.value.length>0&&u(this,"length",n,e,{received:`${n.value.length}`}),n}}}function De(t,n){return{kind:"validation",type:"ends_with",reference:De,async:!1,expects:`"${t}"`,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.endsWith(this.requirement)&&u(this,"end",e,s,{received:`"${e.value.slice(-this.requirement.length)}"`}),e}}}function Ne(t,n){return{kind:"validation",type:"every_item",reference:Ne,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.every(this.requirement)&&u(this,"item",e,s),e}}}function We(t,n){let e=f(t);return{kind:"validation",type:"excludes",reference:We,async:!1,expects:`!${e}`,requirement:t,message:n,_run(s,r){return s.typed&&s.value.includes(this.requirement)&&u(this,"content",s,r,{received:e}),s}}}function Ve(t){return{kind:"transformation",type:"filter_items",reference:Ve,async:!1,operation:t,_run(n){return n.value=n.value.filter(this.operation),n}}}function Ce(t){return{kind:"transformation",type:"find_item",reference:Ce,async:!1,operation:t,_run(n){return n.value=n.value.find(this.operation),n}}}function Le(t){return{kind:"validation",type:"finite",reference:Le,async:!1,expects:null,requirement:Number.isFinite,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&u(this,"finite",n,e),n}}}var Ke={md4:32,md5:32,sha1:40,sha256:64,sha384:96,sha512:128,ripemd128:32,ripemd160:40,tiger128:32,tiger160:40,tiger192:48,crc32:8,crc32b:8,adler32:8};function $e(t,n){return{kind:"validation",type:"hash",reference:$e,expects:null,async:!1,requirement:RegExp(t.map(e=>`^[a-f0-9]{${Ke[e]}}$`).join("|"),"iu"),message:n,_run(e,s){return e.typed&&!this.requirement.test(e.value)&&u(this,"hash",e,s),e}}}function ze(t){return{kind:"validation",type:"hexadecimal",reference:ze,async:!1,expects:null,requirement:L,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"hexadecimal",n,e),n}}}function Fe(t){return{kind:"validation",type:"hex_color",reference:Fe,async:!1,expects:null,requirement:K,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"hex color",n,e),n}}}function Ue(t){return{kind:"validation",type:"imei",reference:Ue,async:!1,expects:null,requirement(n){return $.test(n)&&E(n)},message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&u(this,"IMEI",n,e),n}}}function Ge(t,n){let e=f(t);return{kind:"validation",type:"includes",reference:Ge,async:!1,expects:e,requirement:t,message:n,_run(s,r){return s.typed&&!s.value.includes(this.requirement)&&u(this,"content",s,r,{received:`!${e}`}),s}}}function Xe(t){return{kind:"validation",type:"integer",reference:Xe,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&u(this,"integer",n,e),n}}}function He(t){return{kind:"validation",type:"ip",reference:He,async:!1,expects:null,requirement:U,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"IP",n,e),n}}}function Je(t){return{kind:"validation",type:"ipv4",reference:Je,async:!1,expects:null,requirement:z,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"IPv4",n,e),n}}}function Ze(t){return{kind:"validation",type:"ipv6",reference:Ze,async:!1,expects:null,requirement:F,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"IPv6",n,e),n}}}function Qe(t){return{kind:"validation",type:"iso_date",reference:Qe,async:!1,expects:null,requirement:G,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"date",n,e),n}}}function Ye(t){return{kind:"validation",type:"iso_date_time",reference:Ye,async:!1,expects:null,requirement:X,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"date-time",n,e),n}}}function en(t){return{kind:"validation",type:"iso_time",reference:en,async:!1,expects:null,requirement:H,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"time",n,e),n}}}function nn(t){return{kind:"validation",type:"iso_time_second",reference:nn,async:!1,expects:null,requirement:J,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"time-second",n,e),n}}}function tn(t){return{kind:"validation",type:"iso_timestamp",reference:tn,async:!1,expects:null,requirement:Z,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"timestamp",n,e),n}}}function sn(t){return{kind:"validation",type:"iso_week",reference:sn,async:!1,expects:null,requirement:Q,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"week",n,e),n}}}function un(t,n){return{kind:"validation",type:"length",reference:un,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length!==this.requirement&&u(this,"length",e,s,{received:`${e.value.length}`}),e}}}function rn(t){return{kind:"validation",type:"mac",reference:rn,async:!1,expects:null,requirement:ne,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"MAC",n,e),n}}}function In(t){return{kind:"validation",type:"mac48",reference:In,async:!1,expects:null,requirement:Y,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"48-bit MAC",n,e),n}}}function on(t){return{kind:"validation",type:"mac64",reference:on,async:!1,expects:null,requirement:ee,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"64-bit MAC",n,e),n}}}function an(t){return{kind:"transformation",type:"map_items",reference:an,async:!1,operation:t,_run(n){return n.value=n.value.map(this.operation),n}}}function mn(t,n){return{kind:"validation",type:"max_bytes",reference:mn,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let r=new TextEncoder().encode(e.value).length;r>this.requirement&&u(this,"bytes",e,s,{received:`${r}`})}return e}}}function pn(t,n){return{kind:"validation",type:"max_length",reference:pn,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length>this.requirement&&u(this,"length",e,s,{received:`${e.value.length}`}),e}}}function cn(t,n){return{kind:"validation",type:"max_size",reference:cn,async:!1,expects:`<=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size>this.requirement&&u(this,"size",e,s,{received:`${e.value.size}`}),e}}}function Tn(t,n){return{kind:"validation",type:"max_value",reference:Tn,async:!1,expects:`<=${t instanceof Date?t.toJSON():f(t)}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value>this.requirement&&u(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function fn(t,n){return{kind:"validation",type:"mime_type",reference:fn,async:!1,expects:d(t.map(e=>`"${e}"`),"|"),requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement.includes(e.value.type)&&u(this,"MIME type",e,s,{received:`"${e.value.type}"`}),e}}}function dn(t,n){return{kind:"validation",type:"min_bytes",reference:dn,async:!1,expects:`>=${t}`,requirement:t,message:n,_run(e,s){if(e.typed){let r=new TextEncoder().encode(e.value).length;r=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.length=${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size=${t instanceof Date?t.toJSON():f(t)}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value=e.value&&u(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function An(t){return{kind:"validation",type:"octal",reference:An,async:!1,expects:null,requirement:te,message:t,_run(n,e){return n.typed&&!this.requirement.test(n.value)&&u(this,"octal",n,e),n}}}function M(t,n){if(t.issues)for(let e of n)for(let s of t.issues){let r=!1,o=Math.min(e.length,s.path?.length??0);for(let i=0;iu(this,s?.label??"input",n,e,s)}),n}}}function Pn(t){return{kind:"validation",type:"raw_check",reference:Pn,async:!0,expects:null,async _run(n,e){return await t({dataset:n,config:e,addIssue:s=>u(this,s?.label??"input",n,e,s)}),n}}}function jn(t){return{kind:"transformation",type:"raw_transform",reference:jn,async:!1,_run(n,e){let s=t({dataset:n,config:e,addIssue:r=>u(this,r?.label??"input",n,e,r),NEVER:null});return n.issues?n.typed=!1:n.value=s,n}}}function Rn(t){return{kind:"transformation",type:"raw_transform",reference:Rn,async:!0,async _run(n,e){let s=await t({dataset:n,config:e,addIssue:r=>u(this,r?.label??"input",n,e,r),NEVER:null});return n.issues?n.typed=!1:n.value=s,n}}}function vn(){return{kind:"transformation",type:"readonly",reference:vn,async:!1,_run(t){return t}}}function _n(t,n){return{kind:"transformation",type:"reduce_items",reference:_n,async:!1,operation:t,initial:n,_run(e){return e.value=e.value.reduce(this.operation,this.initial),e}}}function qn(t,n){return{kind:"validation",type:"regex",reference:qn,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&!this.requirement.test(e.value)&&u(this,"format",e,s),e}}}function Dn(t){return{kind:"validation",type:"safe_integer",reference:Dn,async:!1,expects:null,requirement:Number.isSafeInteger,message:t,_run(n,e){return n.typed&&!this.requirement(n.value)&&u(this,"safe integer",n,e),n}}}function Nn(t,n){return{kind:"validation",type:"size",reference:Nn,async:!1,expects:`${t}`,requirement:t,message:n,_run(e,s){return e.typed&&e.value.size!==this.requirement&&u(this,"size",e,s,{received:`${e.value.size}`}),e}}}function Wn(t,n){return{kind:"validation",type:"some_item",reference:Wn,async:!1,expects:null,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.some(this.requirement)&&u(this,"item",e,s),e}}}function Vn(t){return{kind:"transformation",type:"sort_items",reference:Vn,async:!1,operation:t,_run(n){return n.value=n.value.sort(this.operation),n}}}function Cn(t,n){return{kind:"validation",type:"starts_with",reference:Cn,async:!1,expects:`"${t}"`,requirement:t,message:n,_run(e,s){return e.typed&&!e.value.startsWith(this.requirement)&&u(this,"start",e,s,{received:`"${e.value.slice(0,this.requirement.length)}"`}),e}}}function Ln(){return{kind:"transformation",type:"to_lower_case",reference:Ln,async:!1,_run(t){return t.value=t.value.toLowerCase(),t}}}function Kn(t){return{kind:"transformation",type:"to_max_value",reference:Kn,async:!1,requirement:t,_run(n){return n.value=n.value>this.requirement?this.requirement:n.value,n}}}function $n(t){return{kind:"transformation",type:"to_min_value",reference:$n,async:!1,requirement:t,_run(n){return n.value=n.value=e.value)&&u(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():f(e.value)}),e}}}function no(t,n){return{...t,_run(e,s){return t._run(e,{...s,...n})}}}function x(t,n,e){return typeof t.fallback=="function"?t.fallback(n,e):t.fallback}function ro(t,n){return{...t,fallback:n,_run(e,s){let r=t._run(e,s);return r.issues?{typed:!0,value:x(this,r,s)}:r}}}function io(t,n){return{...t,fallback:n,async:!0,async _run(e,s){let r=await t._run(e,s);return r.issues?{typed:!0,value:await x(this,r,s)}:r}}}function po(t){let n={};for(let e of t)if(e.path){let s=ie(e);s?(n.nested||(n.nested={}),n.nested[s]?n.nested[s].push(e.message):n.nested[s]=[e.message]):n.other?n.other.push(e.message):n.other=[e.message]}else n.root?n.root.push(e.message):n.root=[e.message];return n}function To(t,n){return{...t,_run(e,s){let r=e.issues&&[...e.issues];if(t._run(e,s),e.issues){for(let o of e.issues)if(!r?.includes(o)){let i=e.value;for(let a of n){let I=i[a],m={type:"unknown",origin:"value",input:i,key:a,value:I};if(o.path?o.path.push(m):o.path=[m],!I)break;i=I}}}return e}}}function yo(t,n){return{...t,async:!0,async _run(e,s){let r=e.issues&&[...e.issues];if(await t._run(e,s),e.issues){for(let o of e.issues)if(!r?.includes(o)){let i=e.value;for(let a of n){let I=i[a],m={type:"unknown",origin:"value",input:i,key:a,value:I};if(o.path?o.path.push(m):o.path=[m],!I)break;i=I}}}return e}}}function y(t,n,e){return typeof t.default=="function"?t.default(n,e):t.default}function ae(t){if("entries"in t){let n={};for(let e in t.entries)n[e]=ae(t.entries[e]);return n}return"items"in t?t.items.map(ae):y(t)}async function me(t){return"entries"in t?Object.fromEntries(await Promise.all(Object.entries(t.entries).map(async([n,e])=>[n,await me(e)]))):"items"in t?Promise.all(t.items.map(me)):y(t)}function pe(t){if("entries"in t){let n={};for(let e in t.entries)n[e]=pe(t.entries[e]);return n}return"items"in t?t.items.map(pe):x(t)}async function ce(t){return"entries"in t?Object.fromEntries(await Promise.all(Object.entries(t.entries).map(async([n,e])=>[n,await ce(e)]))):"items"in t?Promise.all(t.items.map(ce)):x(t)}function bo(t,n){return!t._run({typed:!1,value:n},{abortEarly:!0}).issues}function et(){return{kind:"schema",type:"any",reference:et,expects:"any",async:!1,_run(t){return t.typed=!0,t}}}function nt(t,n){return{kind:"schema",type:"array",reference:nt,expects:"Array",async:!1,item:t,message:n,_run(e,s){let r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let o=0;othis.item._run({typed:!1,value:i},s)));for(let i=0;iisNaN(+s)).map(([,s])=>s);return{kind:"schema",type:"enum",reference:at,expects:d(e.map(f),"|"),async:!1,enum:t,options:e,message:n,_run(s,r){return this.options.includes(s.value)?s.typed=!0:u(this,"type",s,r),s}}}function mt(t){return{kind:"schema",type:"file",reference:mt,expects:"File",async:!1,message:t,_run(n,e){return n.value instanceof File?n.typed=!0:u(this,"type",n,e),n}}}function pt(t){return{kind:"schema",type:"function",reference:pt,expects:"Function",async:!1,message:t,_run(n,e){return typeof n.value=="function"?n.typed=!0:u(this,"type",n,e),n}}}function ct(t,n){return{kind:"schema",type:"instance",reference:ct,expects:t.name,async:!1,class:t,message:n,_run(e,s){return e.value instanceof this.class?e.typed=!0:u(this,"type",e,s),e}}}function g(t,n){if(typeof t==typeof n){if(t===n||t instanceof Date&&n instanceof Date&&+t==+n)return{value:t};if(t&&n&&t.constructor===Object&&n.constructor===Object){for(let e in n)if(e in t){let s=g(t[e],n[e]);if(s.issue)return s;t[e]=s.value}else t[e]=n[e];return{value:t}}if(Array.isArray(t)&&Array.isArray(n)&&t.length===n.length){for(let e=0;ee.expects),"&"),async:!1,options:t,message:n,_run(e,s){if(this.options.length){let r=e.value,o;e.typed=!0;for(let i of this.options){let a=i._run({typed:!1,value:r},s);if(a.issues&&(e.issues?e.issues.push(...a.issues):e.issues=a.issues,s.abortEarly)){e.typed=!1;break}a.typed||(e.typed=!1),e.typed&&(o?o.push(a.value):o=[a.value])}if(e.typed){e.value=o[0];for(let i=1;ie.expects),"&"),async:!0,options:t,message:n,async _run(e,s){if(this.options.length){let r=e.value,o;e.typed=!0;let i=await Promise.all(this.options.map(a=>a._run({typed:!1,value:r},s)));for(let a of i){if(a.issues&&(e.issues?e.issues.push(...a.issues):e.issues=a.issues,s.abortEarly)){e.typed=!1;break}a.typed||(e.typed=!1),e.typed&&(o?o.push(a.value):o=[a.value])}if(e.typed){e.value=o[0];for(let a=1;a{let I=r[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in r)&&(e.value[i]=I.value)}if(!e.issues||!s.abortEarly)for(let i in r)l(r,i)&&!(i in this.entries)&&(e.value[i]=r[i])}else u(this,"type",e,s);return e}}}function xt(t,n){return{kind:"schema",type:"loose_tuple",reference:xt,expects:"Array",async:!1,items:t,message:n,_run(e,s){let r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let o=0;o{let I=r[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}if(!e.issues||!s.abortEarly)for(let i=this.items.length;iPromise.all([a,I,this.key._run({typed:!1,value:a},r),this.value._run({typed:!1,value:I},r)])));for(let[a,I,m,p]of i){if(m.issues){let c={type:"map",origin:"key",input:o,key:a,value:I};for(let T of m.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=m.issues),r.abortEarly){s.typed=!1;break}}if(p.issues){let c={type:"map",origin:"value",input:o,key:a,value:I};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}(!m.typed||!p.typed)&&(s.typed=!1),s.value.set(m.value,p.value)}}else u(this,"type",s,r);return s}}}function St(t){return{kind:"schema",type:"nan",reference:St,expects:"NaN",async:!1,message:t,_run(n,e){return Number.isNaN(n.value)?n.typed=!0:u(this,"type",n,e),n}}}function Bt(t){return{kind:"schema",type:"never",reference:Bt,expects:"never",async:!1,message:t,_run(n,e){return u(this,"type",n,e),n}}}function At(t,n){return{kind:"schema",type:"non_nullable",reference:At,expects:"!null",async:!1,wrapped:t,message:n,_run(e,s){return e.value===null?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function bt(t,n){return{kind:"schema",type:"non_nullable",reference:bt,expects:"!null",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===null?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function Et(t,n){return{kind:"schema",type:"non_nullish",reference:Et,expects:"(!null & !undefined)",async:!1,wrapped:t,message:n,_run(e,s){return e.value===null||e.value===void 0?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function Mt(t,n){return{kind:"schema",type:"non_nullish",reference:Mt,expects:"(!null & !undefined)",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===null||e.value===void 0?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function P(t,n){return{kind:"schema",type:"non_optional",reference:P,expects:"!undefined",async:!1,wrapped:t,message:n,_run(e,s){return e.value===void 0?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function j(t,n){return{kind:"schema",type:"non_optional",reference:j,expects:"!undefined",async:!0,wrapped:t,message:n,async _run(e,s){return e.value===void 0?(u(this,"type",e,s),e):this.wrapped._run(e,s)}}}function Pt(t){return{kind:"schema",type:"null",reference:Pt,expects:"null",async:!1,message:t,_run(n,e){return n.value===null?n.typed=!0:u(this,"type",n,e),n}}}function jt(t,...n){let e={kind:"schema",type:"nullable",reference:jt,expects:`(${t.expects} | null)`,async:!1,wrapped:t,_run(s,r){return s.value===null&&("default"in this&&(s.value=y(this,s,r)),s.value===null)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function Rt(t,...n){let e={kind:"schema",type:"nullable",reference:Rt,expects:`(${t.expects} | null)`,async:!0,wrapped:t,async _run(s,r){return s.value===null&&("default"in this&&(s.value=await y(this,s,r)),s.value===null)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function vt(t,...n){let e={kind:"schema",type:"nullish",reference:vt,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,_run(s,r){return(s.value===null||s.value===void 0)&&("default"in this&&(s.value=y(this,s,r)),s.value===null||s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function _t(t,...n){let e={kind:"schema",type:"nullish",reference:_t,expects:`(${t.expects} | null | undefined)`,async:!0,wrapped:t,async _run(s,r){return(s.value===null||s.value===void 0)&&("default"in this&&(s.value=await y(this,s,r)),s.value===null||s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function qt(t){return{kind:"schema",type:"number",reference:qt,expects:"number",async:!1,message:t,_run(n,e){return typeof n.value=="number"&&!isNaN(n.value)?n.typed=!0:u(this,"type",n,e),n}}}function Dt(t,n){return{kind:"schema",type:"object",reference:Dt,expects:"Object",async:!1,entries:t,message:n,_run(e,s){let r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};for(let o in this.entries){let i=r[o],a=this.entries[o]._run({typed:!1,value:i},s);if(a.issues){let I={type:"object",origin:"value",input:r,key:o,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||o in r)&&(e.value[o]=a.value)}}else u(this,"type",e,s);return e}}}function Nt(t,n){return{kind:"schema",type:"object",reference:Nt,expects:"Object",async:!0,entries:t,message:n,async _run(e,s){let r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};let o=await Promise.all(Object.entries(this.entries).map(async([i,a])=>{let I=r[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in r)&&(e.value[i]=I.value)}}else u(this,"type",e,s);return e}}}function Wt(t,n,e){return{kind:"schema",type:"object_with_rest",reference:Wt,expects:"Object",async:!1,entries:t,rest:n,message:e,_run(s,r){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};for(let i in this.entries){let a=o[i],I=this.entries[i]._run({typed:!1,value:a},r);if(I.issues){let m={type:"object",origin:"value",input:o,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],s.issues?.push(p);if(s.issues||(s.issues=I.issues),r.abortEarly){s.typed=!1;break}}I.typed||(s.typed=!1),(I.value!==void 0||i in o)&&(s.value[i]=I.value)}if(!s.issues||!r.abortEarly){for(let i in o)if(l(o,i)&&!(i in this.entries)){let a=o[i],I=this.rest._run({typed:!1,value:a},r);if(I.issues){let m={type:"object",origin:"value",input:o,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],s.issues?.push(p);if(s.issues||(s.issues=I.issues),r.abortEarly){s.typed=!1;break}}I.typed||(s.typed=!1),s.value[i]=I.value}}}else u(this,"type",s,r);return s}}}function Vt(t,n,e){return{kind:"schema",type:"object_with_rest",reference:Vt,expects:"Object",async:!0,entries:t,rest:n,message:e,async _run(s,r){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};let[i,a]=await Promise.all([Promise.all(Object.entries(this.entries).map(async([I,m])=>{let p=o[I];return[I,p,await m._run({typed:!1,value:p},r)]})),Promise.all(Object.entries(o).filter(([I])=>l(o,I)&&!(I in this.entries)).map(async([I,m])=>[I,m,await this.rest._run({typed:!1,value:m},r)]))]);for(let[I,m,p]of i){if(p.issues){let c={type:"object",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),(p.value!==void 0||I in o)&&(s.value[I]=p.value)}if(!s.issues||!r.abortEarly)for(let[I,m,p]of a){if(p.issues){let c={type:"object",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value[I]=p.value}}else u(this,"type",s,r);return s}}}function R(t,...n){let e={kind:"schema",type:"optional",reference:R,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,_run(s,r){return s.value===void 0&&("default"in this&&(s.value=y(this,s,r)),s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function v(t,...n){let e={kind:"schema",type:"optional",reference:v,expects:`(${t.expects} | undefined)`,async:!0,wrapped:t,async _run(s,r){return s.value===void 0&&("default"in this&&(s.value=await y(this,s,r)),s.value===void 0)?(s.typed=!0,s):this.wrapped._run(s,r)}};return 0 in n&&(e.default=n[0]),e}function _(t,n){return{kind:"schema",type:"picklist",reference:_,expects:d(t.map(f),"|"),async:!1,options:t,message:n,_run(e,s){return this.options.includes(e.value)?e.typed=!0:u(this,"type",e,s),e}}}function Ct(t){return{kind:"schema",type:"promise",reference:Ct,expects:"Promise",async:!1,message:t,_run(n,e){return n.value instanceof Promise?n.typed=!0:u(this,"type",n,e),n}}}function Lt(t,n,e){return{kind:"schema",type:"record",reference:Lt,expects:"Object",async:!1,key:t,value:n,message:e,_run(s,r){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};for(let i in o)if(l(o,i)){let a=o[i],I=this.key._run({typed:!1,value:i},r);if(I.issues){let p={type:"object",origin:"key",input:o,key:i,value:a};for(let c of I.issues)c.path=[p],s.issues?.push(c);if(s.issues||(s.issues=I.issues),r.abortEarly){s.typed=!1;break}}let m=this.value._run({typed:!1,value:a},r);if(m.issues){let p={type:"object",origin:"value",input:o,key:i,value:a};for(let c of m.issues)c.path?c.path.unshift(p):c.path=[p],s.issues?.push(c);if(s.issues||(s.issues=m.issues),r.abortEarly){s.typed=!1;break}}(!I.typed||!m.typed)&&(s.typed=!1),I.typed&&(s.value[I.value]=m.value)}}else u(this,"type",s,r);return s}}}function Kt(t,n,e){return{kind:"schema",type:"record",reference:Kt,expects:"Object",async:!0,key:t,value:n,message:e,async _run(s,r){let o=s.value;if(o&&typeof o=="object"){s.typed=!0,s.value={};let i=await Promise.all(Object.entries(o).filter(([a])=>l(o,a)).map(([a,I])=>Promise.all([a,I,this.key._run({typed:!1,value:a},r),this.value._run({typed:!1,value:I},r)])));for(let[a,I,m,p]of i){if(m.issues){let c={type:"object",origin:"key",input:o,key:a,value:I};for(let T of m.issues)T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=m.issues),r.abortEarly){s.typed=!1;break}}if(p.issues){let c={type:"object",origin:"value",input:o,key:a,value:I};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}(!m.typed||!p.typed)&&(s.typed=!1),m.typed&&(s.value[m.value]=p.value)}}else u(this,"type",s,r);return s}}}function $t(t,n){return{kind:"schema",type:"set",reference:$t,expects:"Set",async:!1,value:t,message:n,_run(e,s){let r=e.value;if(r instanceof Set){e.typed=!0,e.value=new Set;for(let o of r){let i=this.value._run({typed:!1,value:o},s);if(i.issues){let a={type:"set",origin:"value",input:r,key:null,value:o};for(let I of i.issues)I.path?I.path.unshift(a):I.path=[a],e.issues?.push(I);if(e.issues||(e.issues=i.issues),s.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.add(i.value)}}else u(this,"type",e,s);return e}}}function zt(t,n){return{kind:"schema",type:"set",reference:zt,expects:"Set",async:!0,value:t,message:n,async _run(e,s){let r=e.value;if(r instanceof Set){e.typed=!0,e.value=new Set;let o=await Promise.all([...r].map(async i=>[i,await this.value._run({typed:!1,value:i},s)]));for(let[i,a]of o){if(a.issues){let I={type:"set",origin:"value",input:r,key:null,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.add(a.value)}}else u(this,"type",e,s);return e}}}function Ft(t,n){return{kind:"schema",type:"strict_object",reference:Ft,expects:"Object",async:!1,entries:t,message:n,_run(e,s){let r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};for(let o in this.entries){let i=r[o],a=this.entries[o]._run({typed:!1,value:i},s);if(a.issues){let I={type:"object",origin:"value",input:r,key:o,value:i};for(let m of a.issues)m.path?m.path.unshift(I):m.path=[I],e.issues?.push(m);if(e.issues||(e.issues=a.issues),s.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||o in r)&&(e.value[o]=a.value)}if(!e.issues||!s.abortEarly){for(let o in r)if(!(o in this.entries)){let i=r[o];u(this,"type",e,s,{input:i,expected:"never",path:[{type:"object",origin:"value",input:r,key:o,value:i}]});break}}}else u(this,"type",e,s);return e}}}function Ut(t,n){return{kind:"schema",type:"strict_object",reference:Ut,expects:"Object",async:!0,entries:t,message:n,async _run(e,s){let r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};let o=await Promise.all(Object.entries(this.entries).map(async([i,a])=>{let I=r[i];return[i,I,await a._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"object",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),(I.value!==void 0||i in r)&&(e.value[i]=I.value)}if(!e.issues||!s.abortEarly){for(let i in r)if(!(i in this.entries)){let a=r[i];u(this,"type",e,s,{input:a,expected:"never",path:[{type:"object",origin:"value",input:r,key:i,value:a}]});break}}}else u(this,"type",e,s);return e}}}function Gt(t,n){return{kind:"schema",type:"strict_tuple",reference:Gt,expects:"Array",async:!1,items:t,message:n,_run(e,s){let r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let o=0;o{let I=r[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}if(!(e.issues&&s.abortEarly)&&this.items.length{let I=r[a];return[a,I,await i._run({typed:!1,value:I},s)]}));for(let[i,a,I]of o){if(I.issues){let m={type:"array",origin:"value",input:r,key:i,value:a};for(let p of I.issues)p.path?p.path.unshift(m):p.path=[m],e.issues?.push(p);if(e.issues||(e.issues=I.issues),s.abortEarly){e.typed=!1;break}}I.typed||(e.typed=!1),e.value.push(I.value)}}else u(this,"type",e,s);return e}}}function Yt(t,n,e){return{kind:"schema",type:"tuple_with_rest",reference:Yt,expects:"Array",async:!1,items:t,rest:n,message:e,_run(s,r){let o=s.value;if(Array.isArray(o)){s.typed=!0,s.value=[];for(let i=0;i{let p=o[m];return[m,p,await I._run({typed:!1,value:p},r)]})),Promise.all(o.slice(this.items.length).map(async(I,m)=>[m+this.items.length,I,await this.rest._run({typed:!1,value:I},r)]))]);for(let[I,m,p]of i){if(p.issues){let c={type:"array",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value.push(p.value)}if(!s.issues||!r.abortEarly)for(let[I,m,p]of a){if(p.issues){let c={type:"array",origin:"value",input:o,key:I,value:m};for(let T of p.issues)T.path?T.path.unshift(c):T.path=[c],s.issues?.push(T);if(s.issues||(s.issues=p.issues),r.abortEarly){s.typed=!1;break}}p.typed||(s.typed=!1),s.value.push(p.value)}}else u(this,"type",s,r);return s}}}function ns(t){return{kind:"schema",type:"undefined",reference:ns,expects:"undefined",async:!1,message:t,_run(n,e){return n.value===void 0?n.typed=!0:u(this,"type",n,e),n}}}function S(t){let n;if(t)for(let e of t)n?n.push(...e.issues):n=e.issues;return n}function ts(t,n){return{kind:"schema",type:"union",reference:ts,expects:d(t.map(e=>e.expects),"|"),async:!1,options:t,message:n,_run(e,s){let r,o,i;for(let a of this.options){let I=a._run({typed:!1,value:e.value},s);if(I.typed)if(I.issues)o?o.push(I):o=[I];else{r=I;break}else i?i.push(I):i=[I]}if(r)return r;if(o){if(o.length===1)return o[0];u(this,"type",e,s,{issues:S(o)}),e.typed=!0}else{if(i?.length===1)return i[0];u(this,"type",e,s,{issues:S(i)})}return e}}}function ss(t,n){return{kind:"schema",type:"union",reference:ss,expects:d(t.map(e=>e.expects),"|"),async:!0,options:t,message:n,async _run(e,s){let r,o,i;for(let a of this.options){let I=await a._run({typed:!1,value:e.value},s);if(I.typed)if(I.issues)o?o.push(I):o=[I];else{r=I;break}else i?i.push(I):i=[I]}if(r)return r;if(o){if(o.length===1)return o[0];u(this,"type",e,s,{issues:S(o)}),e.typed=!0}else{if(i?.length===1)return i[0];u(this,"type",e,s,{issues:S(i)})}return e}}}function us(){return{kind:"schema",type:"unknown",reference:us,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function b(t,n,e=[]){for(let s of n)s.type==="variant"?b(t,s.options,e):e.push(s.entries[t].expects);return e}function rs(t,n,e){let s;return{kind:"schema",type:"variant",reference:rs,expects:"Object",async:!1,key:t,options:n,message:e,_run(r,o){let i=r.value;if(i&&typeof i=="object"){let a=i[this.key];if(this.key in i){let I;for(let m of this.options)if(m.type==="variant"||!m.entries[this.key]._run({typed:!1,value:a},o).issues){let p=m._run({typed:!1,value:i},o);if(!p.issues)return p;(!I||!I.typed&&p.typed)&&(I=p)}if(I)return I}s||(s=d(b(this.key,this.options),"|")),u(this,"type",r,o,{input:a,expected:s,path:[{type:"object",origin:"value",input:i,key:this.key,value:a}]})}else u(this,"type",r,o);return r}}}function Is(t,n,e){let s;return{kind:"schema",type:"variant",reference:Is,expects:"Object",async:!0,key:t,options:n,message:e,async _run(r,o){let i=r.value;if(i&&typeof i=="object"){let a=i[this.key];if(this.key in i){let I;for(let m of this.options)if(m.type==="variant"||!(await m.entries[this.key]._run({typed:!1,value:a},o)).issues){let p=await m._run({typed:!1,value:i},o);if(!p.issues)return p;(!I||!I.typed&&p.typed)&&(I=p)}if(I)return I}s||(s=d(b(this.key,this.options),"|")),u(this,"type",r,o,{input:a,expected:s,path:[{type:"object",origin:"value",input:i,key:this.key,value:a}]})}else u(this,"type",r,o);return r}}}function os(t){return{kind:"schema",type:"void",reference:os,expects:"void",async:!1,message:t,_run(n,e){return n.value===void 0?n.typed=!0:u(this,"type",n,e),n}}}function om(t,n){return _(Object.keys(t.entries),n)}function am(t,n){let e={...t.entries};for(let s of n)delete e[s];return{...t,entries:e}}function Te(t,n,e){let s=t._run({typed:!1,value:n},k(e));if(s.issues)throw new h(s.issues);return s.value}async function fe(t,n,e){let s=await t._run({typed:!1,value:n},k(e));if(s.issues)throw new h(s.issues);return s.value}function km(t,n){let e=s=>Te(t,s,n);return e.schema=t,e.config=n,e}function Om(t,n){let e=s=>fe(t,s,n);return e.schema=t,e.config=n,e}function Sm(t,n){let e={};for(let s in t.entries)e[s]=!n||n.includes(s)?R(t.entries[s]):t.entries[s];return{...t,entries:e}}function bm(t,n){let e={};for(let s in t.entries)e[s]=!n||n.includes(s)?v(t.entries[s]):t.entries[s];return{...t,entries:e}}function Mm(t,n){let e={};for(let s of n)e[s]=t.entries[s];return{...t,entries:e}}function jm(...t){return{...t[0],pipe:t,_run(n,e){for(let s of t)if(s.kind!=="metadata"){if(n.issues&&(s.kind==="schema"||s.kind==="transformation")){n.typed=!1;break}(!n.issues||!e.abortEarly&&!e.abortPipeEarly)&&(n=s._run(n,e))}return n}}}function vm(...t){return{...t[0],pipe:t,async:!0,async _run(n,e){for(let s of t)if(s.kind!=="metadata"){if(n.issues&&(s.kind==="schema"||s.kind==="transformation")){n.typed=!1;break}(!n.issues||!e.abortEarly&&!e.abortPipeEarly)&&(n=await s._run(n,e))}return n}}}function Dm(t,n,e){let s=Array.isArray(n)?n:void 0,r=Array.isArray(n)?e:n,o={};for(let i in t.entries)o[i]=!s||s.includes(i)?P(t.entries[i],r):t.entries[i];return{...t,entries:o}}function Vm(t,n,e){let s=Array.isArray(n)?n:void 0,r=Array.isArray(n)?e:n,o={};for(let i in t.entries)o[i]=!s||s.includes(i)?j(t.entries[i],r):t.entries[i];return{...t,entries:o}}function de(t,n,e){let s=t._run({typed:!1,value:n},k(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}async function ye(t,n,e){let s=await t._run({typed:!1,value:n},k(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}function Um(t,n){let e=s=>de(t,s,n);return e.schema=t,e.config=n,e}function Hm(t,n){let e=s=>ye(t,s,n);return e.schema=t,e.config=n,e}function Zm(t){return t.wrapped}export{q as BASE64_REGEX,D as BIC_REGEX,N as CUID2_REGEX,W as DECIMAL_REGEX,V as EMAIL_REGEX,C as EMOJI_REGEX,L as HEXADECIMAL_REGEX,K as HEX_COLOR_REGEX,$ as IMEI_REGEX,z as IPV4_REGEX,F as IPV6_REGEX,U as IP_REGEX,G as ISO_DATE_REGEX,X as ISO_DATE_TIME_REGEX,Z as ISO_TIMESTAMP_REGEX,H as ISO_TIME_REGEX,J as ISO_TIME_SECOND_REGEX,Q as ISO_WEEK_REGEX,Y as MAC48_REGEX,ee as MAC64_REGEX,ne as MAC_REGEX,te as OCTAL_REGEX,se as ULID_REGEX,ue as UUID_REGEX,h as ValiError,u as _addIssue,E as _isLuhnAlgo,l as _isValidObjectKey,d as _joinExpects,f as _stringify,et as any,nt as array,tt as arrayAsync,le as awaitAsync,he as base64,xe as bic,st as bigint,ut as blob,rt as boolean,Oe as brand,we as bytes,ge as check,Se as checkAsync,Be as checkItems,no as config,Me as creditCard,Pe as cuid2,It as custom,ot as customAsync,it as date,je as decimal,ps as deleteGlobalConfig,fs as deleteGlobalMessage,ls as deleteSchemaMessage,xs as deleteSpecificMessage,Re as description,ve as email,_e as emoji,qe as empty,De as endsWith,Ms as entriesFromList,at as enum,at as enum_,Ne as everyItem,We as excludes,ro as fallback,io as fallbackAsync,mt as file,Ve as filterItems,Ce as findItem,Le as finite,po as flatten,To as forward,yo as forwardAsync,pt as function,pt as function_,y as getDefault,ae as getDefaults,me as getDefaultsAsync,ie as getDotPath,x as getFallback,pe as getFallbacks,ce as getFallbacksAsync,k as getGlobalConfig,re as getGlobalMessage,Ie as getSchemaMessage,oe as getSpecificMessage,$e as hash,Fe as hexColor,ze as hexadecimal,Ue as imei,Ge as includes,ct as instance,Xe as integer,Tt as intersect,ft as intersectAsync,He as ip,Je as ipv4,Ze as ipv6,bo as is,Rs as isOfKind,_s as isOfType,Ns as isValiError,Qe as isoDate,Ye as isoDateTime,en as isoTime,nn as isoTimeSecond,tn as isoTimestamp,sn as isoWeek,om as keyof,dt as lazy,yt as lazyAsync,un as length,lt as literal,kt as looseObject,ht as looseObjectAsync,xt as looseTuple,Ot as looseTupleAsync,rn as mac,In as mac48,on as mac64,wt as map,gt as mapAsync,an as mapItems,mn as maxBytes,pn as maxLength,cn as maxSize,Tn as maxValue,fn as mimeType,dn as minBytes,yn as minLength,ln as minSize,kn as minValue,hn as multipleOf,St as nan,Bt as never,xn as nonEmpty,At as nonNullable,bt as nonNullableAsync,Et as nonNullish,Mt as nonNullishAsync,P as nonOptional,j as nonOptionalAsync,On as normalize,wn as notBytes,gn as notLength,Sn as notSize,Bn as notValue,Pt as null,Pt as null_,jt as nullable,Rt as nullableAsync,vt as nullish,_t as nullishAsync,qt as number,Dt as object,Nt as objectAsync,Wt as objectWithRest,Vt as objectWithRestAsync,An as octal,am as omit,R as optional,v as optionalAsync,Te as parse,fe as parseAsync,km as parser,Om as parserAsync,Sm as partial,bm as partialAsync,bn as partialCheck,En as partialCheckAsync,Mm as pick,_ as picklist,jm as pipe,vm as pipeAsync,Ct as promise,Mn as rawCheck,Pn as rawCheckAsync,jn as rawTransform,Rn as rawTransformAsync,vn as readonly,Lt as record,Kt as recordAsync,_n as reduceItems,qn as regex,Dm as required,Vm as requiredAsync,Dn as safeInteger,de as safeParse,ye as safeParseAsync,Um as safeParser,Hm as safeParserAsync,$t as set,zt as setAsync,ms as setGlobalConfig,Ts as setGlobalMessage,ys as setSchemaMessage,hs as setSpecificMessage,Nn as size,Wn as someItem,Vn as sortItems,Cn as startsWith,Ft as strictObject,Ut as strictObjectAsync,Gt as strictTuple,Xt as strictTupleAsync,Ht as string,Jt as symbol,Ln as toLowerCase,Kn as toMaxValue,$n as toMinValue,zn as toUpperCase,Fn as transform,Un as transformAsync,Gn as trim,Xn as trimEnd,Hn as trimStart,Zt as tuple,Qt as tupleAsync,Yt as tupleWithRest,es as tupleWithRestAsync,Jn as ulid,ns as undefined,ns as undefined_,ts as union,ss as unionAsync,us as unknown,Zm as unwrap,Zn as url,Qn as uuid,Yn as value,rs as variant,Is as variantAsync,os as void,os as void_}; diff --git a/src/libMPC/node_modules/valibot/package.json b/src/libMPC/node_modules/valibot/package.json new file mode 100644 index 0000000..a6f934c --- /dev/null +++ b/src/libMPC/node_modules/valibot/package.json @@ -0,0 +1,82 @@ +{ + "name": "valibot", + "description": "The modular and type safe schema library for validating structural data", + "version": "0.38.0", + "license": "MIT", + "author": "Fabian Hiller", + "homepage": "https://valibot.dev", + "repository": { + "type": "git", + "url": "https://github.com/fabian-hiller/valibot" + }, + "keywords": [ + "modular", + "typescript", + "schema", + "validation", + "parsing", + "bundle-size", + "type-safe", + "runtime" + ], + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "play": "tsm ./playground.ts", + "test": "vitest --typecheck", + "coverage": "vitest run --coverage --isolate", + "lint": "eslint \"src/**/*.ts*\" && tsc --noEmit", + "eslint.fix": "eslint \"src/**/*.ts*\" --fix", + "format": "prettier --write ./src", + "format.check": "prettier --check ./src", + "build": "tsup", + "publish.npm": "npm publish", + "publish.jsr": "npx jsr publish" + }, + "devDependencies": { + "@types/eslint": "^8.56.10", + "@typescript-eslint/eslint-plugin": "^7.15.0", + "@typescript-eslint/parser": "^7.15.0", + "@vitest/coverage-v8": "^1.6.0", + "eslint": "^8.57.0", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-jsdoc": "^48.5.2", + "eslint-plugin-redos-detector": "^2.4.0", + "eslint-plugin-regexp": "^2.6.0", + "eslint-plugin-security": "^2.1.1", + "jsdom": "^24.1.0", + "tsm": "^2.3.0", + "tsup": "^8.1.0", + "typescript": "^5.5.3", + "vite": "^5.3.3", + "vitest": "1.6.0" + }, + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/LICENSE b/src/libMPC/node_modules/varuint-bitcoin/LICENSE new file mode 100644 index 0000000..7be1d07 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2016 Kirill Fomichev + +Parts of this software are based on https://github.com/mappum/bitcoin-protocol +Copyright (c) 2016 Matt Bell + +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. diff --git a/src/libMPC/node_modules/varuint-bitcoin/README.md b/src/libMPC/node_modules/varuint-bitcoin/README.md new file mode 100644 index 0000000..0dee44d --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/README.md @@ -0,0 +1,21 @@ +# varuint-bitcoin + +[![NPM Package](https://img.shields.io/npm/v/varuint-bitcoin.svg?style=flat-square)](https://www.npmjs.org/package/varuint-bitcoin) +[![Build Status](https://img.shields.io/travis/bitcoinjs/varuint-bitcoin.svg?branch=master&style=flat-square)](https://travis-ci.org/bitcoinjs/varuint-bitcoin) + +[![abstract-encoding](https://img.shields.io/badge/abstract--encoding-compliant-brightgreen.svg?style=flat-square)](https://github.com/mafintosh/abstract-encoding) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +encode/decode number as [bitcoin variable length integer](https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer) + +| value | storage length (bytes) | +|:------:|:--------------:| +| [0, 0xfd) | 1 | +| [0xfd, 0xffff] | 3 | +| [0x010000, 0xffffffff] | 5 | +| [0x0100000000, 0x1fffffffffffff] | 9 | + +## License + +MIT diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/LICENSE b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/LICENSE new file mode 100644 index 0000000..46c1a64 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Jonathan Underwood + +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. diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/README.md b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/README.md new file mode 100644 index 0000000..50e6b42 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/README.md @@ -0,0 +1,40 @@ +# Uint8Array Tools + +This library is licensed under MIT. + +## Usage + +Note: `fromHex` and `compare` mimic the `Buffer.from('ff', 'hex')` and +`buf1.compare(buf2)` API. Their behavior should be the same in the browser +as well as in Node. + +```js +import * as uint8arraytools from "uint8array-tools"; +uint8arraytools.fromHex("ff"); +// Uint8Array(1) [ 255 ] +uint8arraytools.toHex(Uint8Array.from([0xff])); +// 'ff' +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0x01])); +// 1 +uint8arraytools.compare(Uint8Array.from([0xff]), Uint8Array.from([0xff])); +// 0 +uint8arraytools.compare(Uint8Array.from([0x01]), Uint8Array.from([0xff])); +// -1 +uint8arraytools.fromUtf8("tools"); +// Uint8Array(5) [ 116, 111, 111, 108, 115 ] +uint8arraytools.toUtf8(Uint8Array.from([116, 111, 111, 108, 115])); +// tools +uint8arraytools.concat([Uint8Array.from([1]), Uint8Array.from([2])]); +// Uint8Array(2) [ 1, 2 ] +uint8arraytools.fromBase64("dG9vbHM="); +// Uint8Array(3) [ 182, 138, 37 ] +uint8arraytools.toBase64(Uint8Array.from([116, 111, 111, 108, 115])); +// dG9vbHM= + +const uint8array = new Uint8Array(2); +uint8arraytools.writeUInt16(uint8array, 0, 0xffff - 1, "LE"); +uint8array; +// Uint8Array(2) [ 254, 255 ] +uint8arraytools.readUInt16(uint8array, 0, "LE"); +// 65534 +``` diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/package.json b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/package.json new file mode 100644 index 0000000..2d5fb07 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/package.json @@ -0,0 +1,66 @@ +{ + "name": "uint8array-tools", + "version": "0.0.8", + "description": "A library for dealing with Uint8Arrays.", + "homepage": "https://github.com/bitcoinjs/uint8array-tools#readme", + "bugs": { + "url": "https://github.com/bitcoinjs/uint8array-tools/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/uint8array-tools.git" + }, + "main": "./src/cjs/index.cjs", + "exports": { + "node": { + "module": "./src/mjs/index.js", + "require": "./src/cjs/index.cjs", + "import": "./src/mjs/index.js", + "types": "./src/cjs/index.d.ts" + }, + "browser": "./src/mjs/browser.js", + "default": "./src/mjs/browser.js", + "types": "./src/cjs/index.d.ts" + }, + "types": "src/cjs/index.d.ts", + "type": "module", + "scripts": { + "build": "npm run clean && npm run build-ts && npm run convert-cjs && rm -f ./src/cjs/browser.d.ts", + "build-ts": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json", + "clean": "rm -rf ./src/* && rm -rf ./coverage && rm -f ./package-lock.json", + "convert-cjs": "for f in ./src/cjs/*.js; do mv -- \"$f\" \"${f%.js}.cjs\"; done", + "coverage": "npm run unit -- --coverage", + "eslint": "eslint ts_src/*.ts", + "format": "npm run eslint -- --fix", + "gitdiff:ci": "npm run build && git diff --exit-code", + "lint": "npm run eslint", + "test": "npm run unit", + "unit": "jest --config=jest.json --runInBand" + }, + "keywords": [ + "uint8array", + "hex", + "tools" + ], + "files": [ + "src" + ], + "author": "Jonathan Underwood (junderwood@bitcoinbank.co.jp)", + "license": "MIT", + "devDependencies": { + "@types/jest": "27.0.2", + "@types/node": "16.11.1", + "@typescript-eslint/eslint-plugin": "5.0.0", + "@typescript-eslint/parser": "5.0.0", + "eslint": "8.0.1", + "eslint-config-prettier": "8.3.0", + "eslint-plugin-prettier": "4.0.0", + "jest": "27.2.5", + "prettier": "2.4.1", + "ts-jest": "27.0.7", + "typescript": "4.4.4" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/browser.cjs b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/browser.cjs new file mode 100644 index 0000000..8c1facf --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/browser.cjs @@ -0,0 +1,261 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readUInt64 = exports.readUInt32 = exports.readUInt16 = exports.readUInt8 = exports.writeUInt64 = exports.writeUInt32 = exports.writeUInt16 = exports.writeUInt8 = exports.compare = exports.fromBase64 = exports.toBase64 = exports.fromHex = exports.toHex = exports.concat = exports.fromUtf8 = exports.toUtf8 = void 0; +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder(); +function toUtf8(bytes) { + return DECODER.decode(bytes); +} +exports.toUtf8 = toUtf8; +function fromUtf8(s) { + return ENCODER.encode(s); +} +exports.fromUtf8 = fromUtf8; +function concat(arrays) { + const totalLength = arrays.reduce((a, b) => a + b.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} +exports.concat = concat; +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +exports.toHex = toHex; +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +exports.fromHex = fromHex; +function toBase64(bytes) { + return btoa(String.fromCharCode(...bytes)); +} +exports.toBase64 = toBase64; +function fromBase64(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +exports.fromBase64 = fromBase64; +// Same behavior as Buffer.compare() +function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} +exports.compare = compare; +function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0xff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xff}. Received ${value}`); + } + buffer[offset] = value; +} +exports.writeUInt8 = writeUInt8; +function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } +} +exports.writeUInt16 = writeUInt16; +function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } +} +exports.writeUInt32 = writeUInt32; +function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } +} +exports.writeUInt64 = writeUInt64; +function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + return buffer[offset]; +} +exports.readUInt8 = readUInt8; +function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = (num << 8) + buffer[offset + 1]; + num = (num << 8) + buffer[offset]; + return num; + } + else { + let num = 0; + num = (num << 8) + buffer[offset]; + num = (num << 8) + buffer[offset + 1]; + return num; + } +} +exports.readUInt16 = readUInt16; +function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset]) >>> 0; + return num; + } + else { + let num = 0; + num = ((num << 8) + buffer[offset]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + return num; + } +} +exports.readUInt32 = readUInt32; +function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return num; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return num; + } +} +exports.readUInt64 = readUInt64; diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.cjs b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.cjs new file mode 100644 index 0000000..8665c71 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.cjs @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readUInt64 = exports.readUInt32 = exports.readUInt16 = exports.readUInt8 = exports.writeUInt64 = exports.writeUInt32 = exports.writeUInt16 = exports.writeUInt8 = exports.compare = exports.fromBase64 = exports.toBase64 = exports.fromHex = exports.toHex = exports.concat = exports.fromUtf8 = exports.toUtf8 = void 0; +function toUtf8(bytes) { + return Buffer.from(bytes || []).toString(); +} +exports.toUtf8 = toUtf8; +function fromUtf8(s) { + return Uint8Array.from(Buffer.from(s || "", "utf8")); +} +exports.fromUtf8 = fromUtf8; +function concat(arrays) { + return Uint8Array.from(Buffer.concat(arrays)); +} +exports.concat = concat; +function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +exports.toHex = toHex; +function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +exports.fromHex = fromHex; +function toBase64(bytes) { + return Buffer.from(bytes).toString("base64"); +} +exports.toBase64 = toBase64; +function fromBase64(base64) { + return Uint8Array.from(Buffer.from(base64 || "", "base64")); +} +exports.fromBase64 = fromBase64; +function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} +exports.compare = compare; +function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeUInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); +} +exports.writeUInt8 = writeUInt8; +function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeUInt16LE(value, 0); + } + else { + buf.writeUInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +exports.writeUInt16 = writeUInt16; +function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeUInt32LE(value, 0); + } + else { + buf.writeUInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +exports.writeUInt32 = writeUInt32; +function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buf.writeBigUInt64LE(value, 0); + } + else { + buf.writeBigUInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +exports.writeUInt64 = writeUInt64; +function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readUInt8(offset); +} +exports.readUInt8 = readUInt8; +function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt16LE(offset); + } + else { + return buf.readUInt16BE(offset); + } +} +exports.readUInt16 = readUInt16; +function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt32LE(offset); + } + else { + return buf.readUInt32BE(offset); + } +} +exports.readUInt32 = readUInt32; +function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readBigUInt64LE(offset); + } + else { + return buf.readBigUInt64BE(offset); + } +} +exports.readUInt64 = readUInt64; diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.d.ts b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.d.ts new file mode 100644 index 0000000..5cbe104 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/cjs/index.d.ts @@ -0,0 +1,18 @@ +export declare function toUtf8(bytes: Uint8Array): string; +export declare function fromUtf8(s: string): Uint8Array; +export declare function concat(arrays: Uint8Array[]): Uint8Array; +export declare function toHex(bytes: Uint8Array): string; +export declare function fromHex(hexString: string): Uint8Array; +export declare function toBase64(bytes: Uint8Array): string; +export declare function fromBase64(base64: string): Uint8Array; +export declare type CompareResult = -1 | 0 | 1; +export declare function compare(v1: Uint8Array, v2: Uint8Array): CompareResult; +export declare type endian = "LE" | "BE" | "le" | "be"; +export declare function writeUInt8(buffer: Uint8Array, offset: number, value: number): void; +export declare function writeUInt16(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): void; +export declare function writeUInt32(buffer: Uint8Array, offset: number, value: number, littleEndian: endian): void; +export declare function writeUInt64(buffer: Uint8Array, offset: number, value: bigint, littleEndian: endian): void; +export declare function readUInt8(buffer: Uint8Array, offset: number): number; +export declare function readUInt16(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readUInt32(buffer: Uint8Array, offset: number, littleEndian: endian): number; +export declare function readUInt64(buffer: Uint8Array, offset: number, littleEndian: endian): bigint; diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/browser.js b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/browser.js new file mode 100644 index 0000000..aaab7e4 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/browser.js @@ -0,0 +1,242 @@ +const HEX_STRINGS = "0123456789abcdefABCDEF"; +const HEX_CODES = HEX_STRINGS.split("").map((c) => c.codePointAt(0)); +const HEX_CODEPOINTS = Array(256) + .fill(true) + .map((_, i) => { + const s = String.fromCodePoint(i); + const index = HEX_STRINGS.indexOf(s); + // ABCDEF will use 10 - 15 + return index < 0 ? undefined : index < 16 ? index : index - 6; +}); +const ENCODER = new TextEncoder(); +const DECODER = new TextDecoder(); +export function toUtf8(bytes) { + return DECODER.decode(bytes); +} +export function fromUtf8(s) { + return ENCODER.encode(s); +} +export function concat(arrays) { + const totalLength = arrays.reduce((a, b) => a + b.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} +// There are two implementations. +// One optimizes for length of the bytes, and uses TextDecoder. +// One optimizes for iteration count, and appends strings. +// This removes the overhead of TextDecoder. +export function toHex(bytes) { + const b = bytes || new Uint8Array(); + return b.length > 512 ? _toHexLengthPerf(b) : _toHexIterPerf(b); +} +function _toHexIterPerf(bytes) { + let s = ""; + for (let i = 0; i < bytes.length; ++i) { + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] >> 4]]]; + s += HEX_STRINGS[HEX_CODEPOINTS[HEX_CODES[bytes[i] & 15]]]; + } + return s; +} +function _toHexLengthPerf(bytes) { + const hexBytes = new Uint8Array(bytes.length * 2); + for (let i = 0; i < bytes.length; ++i) { + hexBytes[i * 2] = HEX_CODES[bytes[i] >> 4]; + hexBytes[i * 2 + 1] = HEX_CODES[bytes[i] & 15]; + } + return DECODER.decode(hexBytes); +} +// Mimics Buffer.from(x, 'hex') logic +// Stops on first non-hex string and returns +// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 +export function fromHex(hexString) { + const hexBytes = ENCODER.encode(hexString || ""); + const resultBytes = new Uint8Array(Math.floor(hexBytes.length / 2)); + let i; + for (i = 0; i < resultBytes.length; i++) { + const a = HEX_CODEPOINTS[hexBytes[i * 2]]; + const b = HEX_CODEPOINTS[hexBytes[i * 2 + 1]]; + if (a === undefined || b === undefined) { + break; + } + resultBytes[i] = (a << 4) | b; + } + return i === resultBytes.length ? resultBytes : resultBytes.slice(0, i); +} +export function toBase64(bytes) { + return btoa(String.fromCharCode(...bytes)); +} +export function fromBase64(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +// Same behavior as Buffer.compare() +export function compare(v1, v2) { + const minLength = Math.min(v1.length, v2.length); + for (let i = 0; i < minLength; ++i) { + if (v1[i] !== v2[i]) { + return v1[i] < v2[i] ? -1 : 1; + } + } + return v1.length === v2.length ? 0 : v1.length > v2.length ? 1 : -1; +} +export function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + if (value > 0xff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xff}. Received ${value}`); + } + buffer[offset] = value; +} +export function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + } + else { + buffer[offset] = (value >> 8) & 0xff; + buffer[offset + 1] = value & 0xff; + } +} +export function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffff) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffff}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = value & 0xff; + buffer[offset + 1] = (value >> 8) & 0xff; + buffer[offset + 2] = (value >> 16) & 0xff; + buffer[offset + 3] = (value >> 24) & 0xff; + } + else { + buffer[offset] = (value >> 24) & 0xff; + buffer[offset + 1] = (value >> 16) & 0xff; + buffer[offset + 2] = (value >> 8) & 0xff; + buffer[offset + 3] = value & 0xff; + } +} +export function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buffer[offset] = Number(value & 0xffn); + buffer[offset + 1] = Number((value >> 8n) & 0xffn); + buffer[offset + 2] = Number((value >> 16n) & 0xffn); + buffer[offset + 3] = Number((value >> 24n) & 0xffn); + buffer[offset + 4] = Number((value >> 32n) & 0xffn); + buffer[offset + 5] = Number((value >> 40n) & 0xffn); + buffer[offset + 6] = Number((value >> 48n) & 0xffn); + buffer[offset + 7] = Number((value >> 56n) & 0xffn); + } + else { + buffer[offset] = Number((value >> 56n) & 0xffn); + buffer[offset + 1] = Number((value >> 48n) & 0xffn); + buffer[offset + 2] = Number((value >> 40n) & 0xffn); + buffer[offset + 3] = Number((value >> 32n) & 0xffn); + buffer[offset + 4] = Number((value >> 24n) & 0xffn); + buffer[offset + 5] = Number((value >> 16n) & 0xffn); + buffer[offset + 6] = Number((value >> 8n) & 0xffn); + buffer[offset + 7] = Number(value & 0xffn); + } +} +export function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + return buffer[offset]; +} +export function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = (num << 8) + buffer[offset + 1]; + num = (num << 8) + buffer[offset]; + return num; + } + else { + let num = 0; + num = (num << 8) + buffer[offset]; + num = (num << 8) + buffer[offset + 1]; + return num; + } +} +export function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset]) >>> 0; + return num; + } + else { + let num = 0; + num = ((num << 8) + buffer[offset]) >>> 0; + num = ((num << 8) + buffer[offset + 1]) >>> 0; + num = ((num << 8) + buffer[offset + 2]) >>> 0; + num = ((num << 8) + buffer[offset + 3]) >>> 0; + return num; + } +} +export function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + if (littleEndian === "LE") { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset + 7]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset]); + return num; + } + else { + let num = 0n; + num = (num << 8n) + BigInt(buffer[offset]); + num = (num << 8n) + BigInt(buffer[offset + 1]); + num = (num << 8n) + BigInt(buffer[offset + 2]); + num = (num << 8n) + BigInt(buffer[offset + 3]); + num = (num << 8n) + BigInt(buffer[offset + 4]); + num = (num << 8n) + BigInt(buffer[offset + 5]); + num = (num << 8n) + BigInt(buffer[offset + 6]); + num = (num << 8n) + BigInt(buffer[offset + 7]); + return num; + } +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/index.js b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/index.js new file mode 100644 index 0000000..8e41336 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/node_modules/uint8array-tools/src/mjs/index.js @@ -0,0 +1,123 @@ +export function toUtf8(bytes) { + return Buffer.from(bytes || []).toString(); +} +export function fromUtf8(s) { + return Uint8Array.from(Buffer.from(s || "", "utf8")); +} +export function concat(arrays) { + return Uint8Array.from(Buffer.concat(arrays)); +} +export function toHex(bytes) { + return Buffer.from(bytes || []).toString("hex"); +} +export function fromHex(hexString) { + return Uint8Array.from(Buffer.from(hexString || "", "hex")); +} +export function toBase64(bytes) { + return Buffer.from(bytes).toString("base64"); +} +export function fromBase64(base64) { + return Uint8Array.from(Buffer.from(base64 || "", "base64")); +} +export function compare(v1, v2) { + return Buffer.from(v1).compare(Buffer.from(v2)); +} +export function writeUInt8(buffer, offset, value) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.alloc(1); + buf.writeUInt8(value, 0); + buffer.set(Uint8Array.from(buf), offset); +} +export function writeUInt16(buffer, offset, value, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(2); + if (littleEndian === "LE") { + buf.writeUInt16LE(value, 0); + } + else { + buf.writeUInt16BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +export function writeUInt32(buffer, offset, value, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(4); + if (littleEndian === "LE") { + buf.writeUInt32LE(value, 0); + } + else { + buf.writeUInt32BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +export function writeUInt64(buffer, offset, value, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.alloc(8); + if (value > 0xffffffffffffffffn) { + throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${value}`); + } + if (littleEndian === "LE") { + buf.writeBigUInt64LE(value, 0); + } + else { + buf.writeBigUInt64BE(value, 0); + } + buffer.set(Uint8Array.from(buf), offset); +} +export function readUInt8(buffer, offset) { + if (offset + 1 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + const buf = Buffer.from(buffer); + return buf.readUInt8(offset); +} +export function readUInt16(buffer, offset, littleEndian) { + if (offset + 2 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt16LE(offset); + } + else { + return buf.readUInt16BE(offset); + } +} +export function readUInt32(buffer, offset, littleEndian) { + if (offset + 4 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readUInt32LE(offset); + } + else { + return buf.readUInt32BE(offset); + } +} +export function readUInt64(buffer, offset, littleEndian) { + if (offset + 8 > buffer.length) { + throw new Error("Offset is outside the bounds of Uint8Array"); + } + littleEndian = littleEndian.toUpperCase(); + const buf = Buffer.from(buffer); + if (littleEndian === "LE") { + return buf.readBigUInt64LE(offset); + } + else { + return buf.readBigUInt64BE(offset); + } +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/package.json b/src/libMPC/node_modules/varuint-bitcoin/package.json new file mode 100644 index 0000000..bd4a92d --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/package.json @@ -0,0 +1,51 @@ +{ + "name": "varuint-bitcoin", + "version": "2.0.0", + "type": "module", + "description": "encode/decode number as bitcoin variable length integer", + "homepage": "https://github.com/bitcoinjs/varuint-bitcoin", + "bugs": { + "url": "https://github.com/bitcoinjs/varuint-bitcoin/issues" + }, + "license": "MIT", + "author": "Kirill Fomichev (http://github.com/fanatid)", + "files": [ + "src" + ], + "main": "src/cjs/index.cjs", + "module": "src/esm/index.js", + "types": "src/cjs/index.d.ts", + "exports": { + ".": { + "types": "./src/cjs/index.d.ts", + "import": "./src/esm/index.js", + "require": "./src/cjs/index.cjs" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/varuint-bitcoin.git" + }, + "scripts": { + "build": "npm run clean && tsc -p ./tsconfig.json && tsc -p ./tsconfig.cjs.json; npm run standard -- --fix", + "postbuild": "find src/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\;", + "standard": "ts-standard --ignore test --ignore src", + "gitdiff": "npm run build && git diff --exit-code", + "clean": "rimraf src", + "coverage": "c8 --check-coverage --branches 100 --functions 100 npm run unit", + "lint": "npm run standard", + "test": "npm run lint && npm run coverage", + "unit": "tape test/*.js" + }, + "dependencies": { + "uint8array-tools": "^0.0.8" + }, + "devDependencies": { + "@types/node": "^20.14.8", + "c8": "^10.1.2", + "rimraf": "^5.0.7", + "tape": "^5.3.0", + "ts-standard": "^12.0.2", + "typescript": "^5.1.6" + } +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.cjs b/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.cjs new file mode 100644 index 0000000..7336f35 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.cjs @@ -0,0 +1,115 @@ +'use strict'; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encode = encode; +exports.decode = decode; +exports.encodingLength = encodingLength; +const tools = __importStar(require("uint8array-tools")); +const checkUInt64 = (n) => { + if (n < 0 || n > 0xffffffffffffffffn) { + throw new RangeError('value out of range'); + } +}; +function checkUInt53(n) { + if (n < 0 || n > Number.MAX_SAFE_INTEGER || n % 1 !== 0) + throw new RangeError('value out of range'); +} +function checkUint53OrUint64(n) { + if (typeof n === 'number') + checkUInt53(n); + else + checkUInt64(n); +} +function encode(n, buffer, offset) { + checkUint53OrUint64(n); + if (offset === undefined) + offset = 0; + if (buffer === undefined) { + buffer = new Uint8Array(encodingLength(n)); + } + let bytes = 0; + // 8 bit + if (n < 0xfd) { + buffer.set([Number(n)], offset); + bytes = 1; + // 16 bit + } + else if (n <= 0xffff) { + buffer.set([0xfd], offset); + tools.writeUInt16(buffer, offset + 1, Number(n), 'LE'); + bytes = 3; + // 32 bit + } + else if (n <= 0xffffffff) { + buffer.set([0xfe], offset); + tools.writeUInt32(buffer, offset + 1, Number(n), 'LE'); + bytes = 5; + // 64 bit + } + else { + buffer.set([0xff], offset); + tools.writeUInt64(buffer, offset + 1, BigInt(n), 'LE'); + bytes = 9; + } + return { buffer, bytes }; +} +function decode(buffer, offset) { + if (offset === undefined) + offset = 0; + const first = buffer.at(offset); + if (first === undefined) + throw new Error('buffer too small'); + // 8 bit + if (first < 0xfd) { + return { numberValue: first, bigintValue: BigInt(first), bytes: 1 }; + // 16 bit + } + else if (first === 0xfd) { + const val = tools.readUInt16(buffer, offset + 1, 'LE'); + return { + numberValue: val, + bigintValue: BigInt(val), + bytes: 3 + }; + // 32 bit + } + else if (first === 0xfe) { + const val = tools.readUInt32(buffer, offset + 1, 'LE'); + return { + numberValue: val, + bigintValue: BigInt(val), + bytes: 5 + }; + // 64 bit + } + else { + const number = tools.readUInt64(buffer, offset + 1, 'LE'); + return { numberValue: number <= Number.MAX_SAFE_INTEGER ? Number(number) : null, bigintValue: number, bytes: 9 }; + } +} +function encodingLength(n) { + checkUint53OrUint64(n); + return n < 0xfd ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9; +} diff --git a/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.d.ts b/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.d.ts new file mode 100644 index 0000000..1795091 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/src/cjs/index.d.ts @@ -0,0 +1,10 @@ +export declare function encode(n: number | bigint, buffer?: Uint8Array, offset?: number): { + buffer: Uint8Array; + bytes: number; +}; +export declare function decode(buffer: Uint8Array, offset?: number): { + numberValue: number | null; + bigintValue: bigint; + bytes: number; +}; +export declare function encodingLength(n: number | bigint): number; diff --git a/src/libMPC/node_modules/varuint-bitcoin/src/esm/index.js b/src/libMPC/node_modules/varuint-bitcoin/src/esm/index.js new file mode 100644 index 0000000..ec06d97 --- /dev/null +++ b/src/libMPC/node_modules/varuint-bitcoin/src/esm/index.js @@ -0,0 +1,88 @@ +'use strict'; +import * as tools from 'uint8array-tools'; +const checkUInt64 = (n) => { + if (n < 0 || n > 0xffffffffffffffffn) { + throw new RangeError('value out of range'); + } +}; +function checkUInt53(n) { + if (n < 0 || n > Number.MAX_SAFE_INTEGER || n % 1 !== 0) + throw new RangeError('value out of range'); +} +function checkUint53OrUint64(n) { + if (typeof n === 'number') + checkUInt53(n); + else + checkUInt64(n); +} +export function encode(n, buffer, offset) { + checkUint53OrUint64(n); + if (offset === undefined) + offset = 0; + if (buffer === undefined) { + buffer = new Uint8Array(encodingLength(n)); + } + let bytes = 0; + // 8 bit + if (n < 0xfd) { + buffer.set([Number(n)], offset); + bytes = 1; + // 16 bit + } + else if (n <= 0xffff) { + buffer.set([0xfd], offset); + tools.writeUInt16(buffer, offset + 1, Number(n), 'LE'); + bytes = 3; + // 32 bit + } + else if (n <= 0xffffffff) { + buffer.set([0xfe], offset); + tools.writeUInt32(buffer, offset + 1, Number(n), 'LE'); + bytes = 5; + // 64 bit + } + else { + buffer.set([0xff], offset); + tools.writeUInt64(buffer, offset + 1, BigInt(n), 'LE'); + bytes = 9; + } + return { buffer, bytes }; +} +export function decode(buffer, offset) { + if (offset === undefined) + offset = 0; + const first = buffer.at(offset); + if (first === undefined) + throw new Error('buffer too small'); + // 8 bit + if (first < 0xfd) { + return { numberValue: first, bigintValue: BigInt(first), bytes: 1 }; + // 16 bit + } + else if (first === 0xfd) { + const val = tools.readUInt16(buffer, offset + 1, 'LE'); + return { + numberValue: val, + bigintValue: BigInt(val), + bytes: 3 + }; + // 32 bit + } + else if (first === 0xfe) { + const val = tools.readUInt32(buffer, offset + 1, 'LE'); + return { + numberValue: val, + bigintValue: BigInt(val), + bytes: 5 + }; + // 64 bit + } + else { + const number = tools.readUInt64(buffer, offset + 1, 'LE'); + return { numberValue: number <= Number.MAX_SAFE_INTEGER ? Number(number) : null, bigintValue: number, bytes: 9 }; + } +} +export function encodingLength(n) { + checkUint53OrUint64(n); + return n < 0xfd ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9; +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/LICENSE b/src/libMPC/node_modules/web-streams-polyfill/LICENSE new file mode 100644 index 0000000..9fe85ac --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2024 Mattias Buelens +Copyright (c) 2016 Diwank Singh Tomer + +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. diff --git a/src/libMPC/node_modules/web-streams-polyfill/README.md b/src/libMPC/node_modules/web-streams-polyfill/README.md new file mode 100644 index 0000000..f4023ff --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/README.md @@ -0,0 +1,110 @@ +# web-streams-polyfill + +Web Streams, based on the WHATWG spec reference implementation. + +[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill) +[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill) +[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE) + +## Links + + - [Official spec][spec] + - [Reference implementation][ref-impl] + +## Usage + +This library comes in multiple variants: +* `web-streams-polyfill`: a polyfill that replaces the native stream implementations. + Recommended for use in web apps supporting older browsers through a ` + + + +``` +Usage as a Node module: +```js +var streams = require("web-streams-polyfill/ponyfill"); +var readable = new streams.ReadableStream(); +``` +Usage as a ES2015 module: +```js +import { ReadableStream } from "web-streams-polyfill/ponyfill"; +const readable = new ReadableStream(); +``` + +## Compatibility + +The `polyfill` and `ponyfill` variants work in any ES5-compatible environment that has a global `Promise`. +If you need to support older browsers or Node versions that do not have a native `Promise` implementation +(check the [support table][promise-support]), you must first include a `Promise` polyfill +(e.g. [promise-polyfill][promise-polyfill]). + +The `polyfill/es6` and `ponyfill/es6` variants work in any ES2015-compatible environment. + +The `polyfill/es2018` and `ponyfill/es2018` variants work in any ES2018-compatible environment. + +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`. + +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill]. + +[Reading with a BYOB reader][mdn-byob-read] is available in all variants, but requires `ArrayBuffer.prototype.transfer()` or `structuredClone()` to exist in order to correctly transfer the given view's buffer. If not available, then the buffer won't be transferred during the read. + +## Compliance + +The polyfill implements [version `4dc123a` (13 Nov 2023)][spec-snapshot] of the streams specification. + +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations. +The polyfill aims to pass all tests, although it allows some exceptions for practical reasons: +* The `es2018` variant passes all of the tests. +* The `es6` variant passes the same tests as the `es2018` variant, except for the [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype]. + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018. + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype. +* The `es5` variant passes the same tests as the `es6` variant, except for various tests about specific characteristics of the constructors, properties and methods. + These test failures do not affect the run-time behavior of the polyfill. + For example: + * The `name` property of down-leveled constructors is incorrect. + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect. + * Not all properties and methods are correctly marked as non-enumerable. + * Down-leveled class methods are not correctly marked as non-constructable. + +The type definitions are compatible with the built-in stream types of TypeScript 3.3. + +## Contributors + +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]: + + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr)) + - Anders Riutta ([ariutta](https://github.com/ariutta)) + +[spec]: https://streams.spec.whatwg.org +[ref-impl]: https://github.com/whatwg/streams +[ponyfill]: https://github.com/sindresorhus/ponyfill +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill +[mdn-byob-read]: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader/read +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/4dc123a6e7f7ba89a8c6a7975b021156f39cab52/ +[wpt]: https://github.com/web-platform-tests/wpt/tree/2a298b616b7c865917d7198a287310881cbfdd8d/streams +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/2a298b616b7c865917d7198a287310881cbfdd8d/streams/readable-streams/async-iterator.any.js#L24 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v2.0.0/src/target/es5/stub/async-iterator-prototype.ts +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js new file mode 100644 index 0000000..20a929a --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js @@ -0,0 +1,4765 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es2018.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map new file mode 100644 index 0000000..cffe625 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }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C,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;ICzoBA,MAAME,SAAO,GAAG;QACd,cAAc;QACd,+BAA+B;QAC/B,4BAA4B;QAC5B,yBAAyB;QACzB,2BAA2B;QAC3B,wBAAwB;QAExB,cAAc;QACd,+BAA+B;QAC/B,2BAA2B;QAE3B,yBAAyB;QACzB,oBAAoB;QAEpB,eAAe;QACf,gCAAgC;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,IAAA,KAAK,MAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js new file mode 100644 index 0000000..39e9eae --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.reject.bind(a);function s(e){return new a(e)}function u(e){return s((t=>t(e)))}function c(e){return l(e)}function d(e,t,r){return i.call(e,t,r)}function f(e,t,r){d(d(e,t,r),void 0,o)}function b(e,t){f(e,t)}function m(e,t){f(e,void 0,t)}function h(e,t,r){return d(e,t,r)}function _(e){d(e,void 0,o)}let p=e=>{if("function"==typeof queueMicrotask)p=queueMicrotask;else{const e=u(void 0);p=t=>d(e,t)}return p(e)};function y(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function S(e,t,r){try{return u(y(e,t,r))}catch(e){return c(e)}}class g{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=Symbol("[[AbortSteps]]"),w=Symbol("[[ErrorSteps]]"),R=Symbol("[[CancelSteps]]"),T=Symbol("[[PullSteps]]"),C=Symbol("[[ReleaseSteps]]");function P(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),k(e)}(e):O(e,t._storedError)}function q(e,t){return Er(e._ownerReadableStream,t)}function E(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){O(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function O(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function k(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const A=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function z(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function L(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function F(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function I(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function M(e){return Number(e)}function Y(e){return 0===e?0:e}function Q(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!A(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return A(o)&&0!==o?o:0}function x(e,t){if(!Pr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function N(e){return new ReadableStreamDefaultReader(e)}function H(e,t){e._reader._readRequests.push(t)}function V(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function U(e){return e._reader._readRequests.length}function G(e){const t=e._reader;return void 0!==t&&!!X(t)}class ReadableStreamDefaultReader{constructor(e){if(I(e,1,"ReadableStreamDefaultReader"),x(e,"First parameter"),qr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new g}get closed(){return X(this)?this._closedPromise:c(Z("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(Z("cancel"))}read(){if(!X(this))return c(Z("read"));if(void 0===this._ownerReadableStream)return c(W("read from"));let e,t;const r=s(((r,o)=>{e=r,t=o}));return J(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw Z("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");K(e,t)}(this)}}function X(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function J(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[T](t)}function K(e,t){const r=e._readRequests;e._readRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const ee=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?h(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?h(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=s(((e,o)=>{t=e,r=o}));return J(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,p((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=q(t,e);return E(t),h(r,(()=>({value:e,done:!0})))}return E(t),u({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():c(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):c(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};var ie,le,se;function ue(e){return e.slice()}function ce(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}let de=e=>(de="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,de(e)),fe=e=>(fe="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,fe(e));function be(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ce(n,0,e,t,o),n}function me(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}const he=null!==(se=null!==(ie=Symbol.asyncIterator)&&void 0!==ie?ie:null===(le=Symbol.for)||void 0===le?void 0:le.call(Symbol,"Symbol.asyncIterator"))&&void 0!==se?se:"@@asyncIterator";function _e(e,t="sync",o){if(void 0===o)if("async"===t){if(void 0===(o=me(e,he))){return function(e){const t={[Symbol.iterator]:()=>e.iterator},r=async function*(){return yield*t}();return{iterator:r,nextMethod:r.next,done:!1}}(_e(e,"sync",me(e,Symbol.iterator)))}}else o=me(e,Symbol.iterator);if(void 0===o)throw new TypeError("The object is not iterable");const n=y(o,e,[]);if(!r(n))throw new TypeError("The iterator method must return an object");return{iterator:n,nextMethod:n.next,done:!1}}function pe(e){const t=be(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ye(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Se(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ge(e){e._queue=new g,e._queueTotalSize=0}function ve(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Re(this))throw Ge("view");return this._view}respond(e){if(!Re(this))throw Ge("respond");if(I(e,1,"respond"),e=Q(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");He(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Re(this))throw Ge("respondWithNewView");if(I(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ve(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!we(this))throw Xe("byobRequest");return xe(this)}get desiredSize(){if(!we(this))throw Xe("desiredSize");return Ne(this)}close(){if(!we(this))throw Xe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);$e(this)}enqueue(e){if(!we(this))throw Xe("enqueue");if(I(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);Me(this,e)}error(e=void 0){if(!we(this))throw Xe("error");Ye(this,e)}[R](e){Ce(this),ge(this);const t=this._cancelAlgorithm(e);return Ie(this),t}[T](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Qe(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}H(t,e),Te(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new g,this._pendingPullIntos.push(e)}}}function we(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function Re(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function Te(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(G(t)&&U(t)>0)return!0;if(tt(t)&&et(t)>0)return!0;const r=Ne(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Te(e)),null)),(t=>(Ye(e,t),null)))}function Ce(e){Ae(e),e._pendingPullIntos=new g}function Pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=qe(t);"default"===t.readerType?V(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function qe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Ee(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function We(e,t,r,o){let n;try{n=be(t,r,r+o)}catch(t){throw Ye(e,t),t}Ee(e,n,0,o)}function Be(e,t){t.bytesFilled>0&&We(e,t.buffer,t.byteOffset,t.bytesFilled),Fe(e)}function Oe(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;ce(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,je(e,o,t),n-=o}return a}function je(e,t,r){r.bytesFilled+=t}function ke(e){0===e._queueTotalSize&&e._closeRequested?(Ie(e),Wr(e._controlledReadableByteStream)):Te(e)}function Ae(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function De(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Oe(e,t)&&(Fe(e),Pe(e._controlledReadableByteStream,t))}}function ze(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return ve(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=de(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void Ze(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(Oe(e,d)){const t=qe(d);return ke(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ye(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),Ze(n,o),Te(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Le(e,t){const r=e._pendingPullIntos.peek();Ae(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Fe(e);const r=e._controlledReadableByteStream;if(tt(r))for(;et(r)>0;)Pe(r,Fe(e))}(e,r):function(e,t,r){if(je(0,t,r),"none"===r.readerType)return Be(e,r),void De(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;We(e,r.buffer,t-o,o)}r.bytesFilled-=o,Pe(e._controlledReadableByteStream,r),De(e)}(e,t,r),Te(e)}function Fe(e){return e._pendingPullIntos.shift()}function Ie(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function $e(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ye(e,t),t}}Ie(e),Wr(t)}}function Me(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(fe(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=de(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(fe(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ae(e),t.buffer=de(t.buffer),"none"===t.readerType&&Be(e,t)}if(G(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Qe(e,t._readRequests.shift())}}(e),0===U(r))Ee(e,i,n,a);else{e._pendingPullIntos.length>0&&Fe(e);V(r,new Uint8Array(i,n,a),!1)}else tt(r)?(Ee(e,i,n,a),De(e)):Ee(e,i,n,a);Te(e)}function Ye(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Ce(e),ge(e),Ie(e),Br(r,t))}function Qe(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ke(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function xe(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Ne(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function He(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=de(r.buffer),Le(e,t)}function Ve(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=de(t.buffer),Le(e,o)}function Ue(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ge(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new g,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,Te(t),null)),(e=>(Ye(t,e),null)))}function Ge(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Xe(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Je(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ke(e){return new ReadableStreamBYOBReader(e)}function Ze(e,t){e._reader._readIntoRequests.push(t)}function et(e){return e._reader._readIntoRequests.length}function tt(e){const t=e._reader;return void 0!==t&&!!rt(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(I(e,1,"ReadableStreamBYOBReader"),x(e,"First parameter"),qr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!we(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");P(this,e),this._readIntoRequests=new g}get closed(){return rt(this)?this._closedPromise:c(at("closed"))}cancel(e=void 0){return rt(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(at("cancel"))}read(e,t={}){if(!rt(this))return c(at("read"));if(!ArrayBuffer.isView(e))return c(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return c(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return c(new TypeError("view's buffer must have non-zero byteLength"));if(fe(e.buffer))return c(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return z(e,t),{min:Q(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return c(e)}const o=r.min;if(0===o)return c(new TypeError("options.min must be greater than 0"));if(function(e){return ve(e.constructor)}(e)){if(o>e.byteLength)return c(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return c(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return c(W("read from"));let n,a;const i=s(((e,t)=>{n=e,a=t}));return ot(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!rt(this))throw at("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");nt(e,t)}(this)}}function rt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function ot(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):ze(n._readableStreamController,t,r,o)}function nt(e,t){const r=e._readIntoRequests;e._readIntoRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function at(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function it(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function lt(e){const{size:t}=e;return t||(()=>1)}function st(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:M(r),size:void 0===o?void 0:ut(o,`${t} has member 'size' that`)}}function ut(e,t){return L(e,t),t=>M(e(t))}function ct(e,t,r){return L(e,r),r=>S(e,t,[r])}function dt(e,t,r){return L(e,r),()=>S(e,t,[])}function ft(e,t,r){return L(e,r),r=>y(e,t,[r])}function bt(e,t,r){return L(e,r),(r,o)=>S(e,t,[r,o])}function mt(e,t){if(!yt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const ht="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=st(t,"Second parameter"),o=function(e,t){z(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:ct(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:dt(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:ft(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:bt(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");pt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=lt(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>u(void 0);l=void 0!==t.close?()=>t.close():()=>u(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>u(void 0);zt(e,n,a,i,l,s,r,o)}(this,o,it(r,1),n)}get locked(){if(!yt(this))throw Qt("locked");return St(this)}abort(e=void 0){return yt(this)?St(this)?c(new TypeError("Cannot abort a stream that already has a writer")):gt(this,e):c(Qt("abort"))}close(){return yt(this)?St(this)?c(new TypeError("Cannot close a stream that already has a writer")):Ct(this)?c(new TypeError("Cannot close an already-closing stream")):vt(this):c(Qt("close"))}getWriter(){if(!yt(this))throw Qt("getWriter");return _t(this)}}function _t(e){return new WritableStreamDefaultWriter(e)}function pt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new g,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function yt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function St(e){return void 0!==e._writer}function gt(e,t){var r;if("closed"===e._state||"errored"===e._state)return u(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return u(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=s(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||Rt(e,t),a}function vt(e){const t=e._state;if("closed"===t||"errored"===t)return c(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=s(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&tr(o),Se(n=e._writableStreamController,At,0),It(n),r}function wt(e,t){"writable"!==e._state?Tt(e):Rt(e,t)}function Rt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&Ot(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Tt(e)}function Tt(e){e._state="errored",e._writableStreamController[w]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new g,void 0===e._pendingAbortRequest)return void Pt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Pt(e);f(e._writableStreamController[v](r._reason),(()=>(r._resolve(),Pt(e),null)),(t=>(r._reject(t),Pt(e),null)))}function Ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Pt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Gt(t,e._storedError)}function qt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Jt(e)}(r):tr(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStream.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(I(e,1,"WritableStreamDefaultWriter"),mt(e,"First parameter"),St(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!Ct(e)&&e._backpressure?Jt(this):Zt(this),Vt(this);else if("erroring"===t)Kt(this,e._storedError),Vt(this);else if("closed"===t)Zt(this),Vt(r=this),Xt(r);else{const t=e._storedError;Kt(this,t),Ut(this,t)}var r}get closed(){return Et(this)?this._closedPromise:c(Nt("closed"))}get desiredSize(){if(!Et(this))throw Nt("desiredSize");if(void 0===this._ownerWritableStream)throw Ht("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Ft(t._writableStreamController)}(this)}get ready(){return Et(this)?this._readyPromise:c(Nt("ready"))}abort(e=void 0){return Et(this)?void 0===this._ownerWritableStream?c(Ht("abort")):function(e,t){return gt(e._ownerWritableStream,t)}(this,e):c(Nt("abort"))}close(){if(!Et(this))return c(Nt("close"));const e=this._ownerWritableStream;return void 0===e?c(Ht("close")):Ct(e)?c(new TypeError("Cannot close an already-closing stream")):Wt(this)}releaseLock(){if(!Et(this))throw Nt("releaseLock");void 0!==this._ownerWritableStream&&jt(this)}write(e=void 0){return Et(this)?void 0===this._ownerWritableStream?c(Ht("write to")):kt(this,e):c(Nt("write"))}}function Et(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function Wt(e){return vt(e._ownerWritableStream)}function Bt(e,t){"pending"===e._closedPromiseState?Gt(e,t):function(e,t){Ut(e,t)}(e,t)}function Ot(e,t){"pending"===e._readyPromiseState?er(e,t):function(e,t){Kt(e,t)}(e,t)}function jt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Ot(e,r),Bt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function kt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return $t(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return c(Ht("write to"));const a=r._state;if("errored"===a)return c(r._storedError);if(Ct(r)||"closed"===a)return c(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return c(r._storedError);const i=function(e){return s(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{Se(e,t,r)}catch(t){return void $t(e,t)}const o=e._controlledWritableStream;if(!Ct(o)&&"writable"===o._state){qt(o,Mt(e))}It(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const At={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Dt(this))throw xt("abortReason");return this._abortReason}get signal(){if(!Dt(this))throw xt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!Dt(this))throw xt("error");"writable"===this._controlledWritableStream._state&&Yt(this,e)}[v](e){const t=this._abortAlgorithm(e);return Lt(this),t}[w](){ge(this)}}function Dt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function zt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ge(t),t._abortReason=void 0,t._abortController=function(){if(ht)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Mt(t);qt(e,s);f(u(r()),(()=>(t._started=!0,It(t),null)),(r=>(t._started=!0,wt(e,r),null)))}function Lt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ft(e){return e._strategyHWM-e._queueTotalSize}function It(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===At?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ye(e);const r=e._closeAlgorithm();Lt(e),f(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Xt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),wt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);f(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ye(e),!Ct(r)&&"writable"===t){const t=Mt(e);qt(r,t)}return It(e),null}),(t=>("writable"===r._state&&Lt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,wt(e,t)}(r,t),null)))}(e,r)}function $t(e,t){"writable"===e._controlledWritableStream._state&&Yt(e,t)}function Mt(e){return Ft(e)<=0}function Yt(e,t){const r=e._controlledWritableStream;Lt(e),Rt(r,t)}function Qt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function xt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Nt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Ht(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Vt(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Ut(e,t){Vt(e),Gt(e,t)}function Gt(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Xt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Jt(e){e._readyPromise=s(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Kt(e,t){Jt(e),er(e,t)}function Zt(e){Jt(e),tr(e)}function er(e,t){void 0!==e._readyPromise_reject&&(_(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function tr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const rr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const or=function(){const e=null==rr?void 0:rr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return n(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function nr(e,r,o,n,a,i){const l=N(e),h=_t(r);e._disturbed=!0;let p=!1,y=u(void 0);return s(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const t=void 0!==i.reason?i.reason:new or("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===r._state?gt(r,t):u(void 0))),a||o.push((()=>"readable"===e._state?Er(e,t):u(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,t)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?W(!0,e):q((()=>gt(r,e)),!0,e),null))),P(r,h._closedPromise,(t=>(a?W(!0,t):q((()=>Er(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?W():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return Ct(t)||"closed"===r?u(void 0):"errored"===r?c(t._storedError):Wt(e)}(h))),null),"closed"===w._state?T():b(R,T),Ct(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):q((()=>Er(e,t)),!0,t)}function C(){const e=y;return d(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,t,o){function n(){return f(e(),(()=>B(t,o)),(e=>B(!0,e))),null}p||(p=!0,"writable"!==r._state||Ct(r)?n():b(C(),n))}function W(e,t){p||(p=!0,"writable"!==r._state||Ct(r)?B(e,t):b(C(),(()=>B(e,t))))}function B(e,t){return jt(h),E(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}_(s(((e,r)=>{!function o(n){n?e():d(p?u(!0):d(h._readyPromise,(()=>s(((e,r)=>{J(l,{_chunkSteps:r=>{y=d(kt(h,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),o,r)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ar(this))throw hr("desiredSize");return fr(this)}close(){if(!ar(this))throw hr("close");if(!br(this))throw new TypeError("The stream is not in a state that permits close");ur(this)}enqueue(e=void 0){if(!ar(this))throw hr("enqueue");if(!br(this))throw new TypeError("The stream is not in a state that permits enqueue");return cr(this,e)}error(e=void 0){if(!ar(this))throw hr("error");dr(this,e)}[R](e){ge(this);const t=this._cancelAlgorithm(e);return sr(this),t}[T](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ye(this);this._closeRequested&&0===this._queue.length?(sr(this),Wr(t)):ir(this),e._chunkSteps(r)}else H(t,e),ir(this)}[C](){}}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function ir(e){if(!lr(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ir(e)),null)),(t=>(dr(e,t),null)))}function lr(e){const t=e._controlledReadableStream;if(!br(e))return!1;if(!e._started)return!1;if(qr(t)&&U(t)>0)return!0;return fr(e)>0}function sr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ur(e){if(!br(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(sr(e),Wr(t))}function cr(e,t){if(!br(e))return;const r=e._controlledReadableStream;if(qr(r)&&U(r)>0)V(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw dr(e,t),t}try{Se(e,t,r)}catch(t){throw dr(e,t),t}}ir(e)}function dr(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ge(e),sr(e),Br(r,t))}function fr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function br(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function mr(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ge(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,ir(t),null)),(e=>(dr(t,e),null)))}function hr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function _r(e,t){return we(e._readableStreamController)?function(e){let t,r,o,n,a,i=N(e),l=!1,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Ye(o._readableStreamController,t),Ye(n._readableStreamController,t),f&&b||a(void 0)),null)))}function y(){rt(i)&&(E(i),i=N(e),_(i));J(i,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=pe(t)}catch(t){return Ye(o._readableStreamController,t),Ye(n._readableStreamController,t),void a(Er(e,t))}f||Me(o._readableStreamController,r),b||Me(n._readableStreamController,i),l=!1,c?g():d&&v()}))},_closeSteps:()=>{l=!1,f||$e(o._readableStreamController),b||$e(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&He(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&He(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){X(i)&&(E(i),i=Ke(e),_(i));const s=r?n:o,u=r?o:n;ot(i,t,1,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const o=r?b:f;if(r?f:b)o||Ve(s._readableStreamController,t);else{let r;try{r=pe(t)}catch(t){return Ye(s._readableStreamController,t),Ye(u._readableStreamController,t),void a(Er(e,t))}o||Ve(s._readableStreamController,t),Me(u._readableStreamController,r)}l=!1,c?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||$e(s._readableStreamController),o||$e(u._readableStreamController),void 0!==e&&(t||Ve(s._readableStreamController,e),!o&&u._readableStreamController._pendingPullIntos.length>0&&He(u._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return c=!0,u(void 0);l=!0;const e=xe(o._readableStreamController);return null===e?y():S(e._view,!1),u(void 0)}function v(){if(l)return d=!0,u(void 0);l=!0;const e=xe(n._readableStreamController);return null===e?y():S(e._view,!0),u(void 0)}function w(o){if(f=!0,t=o,b){const o=ue([t,r]),n=Er(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ue([t,r]),n=Er(e,o);a(n)}return h}function T(){}return o=Tr(T,g,w),n=Tr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=N(e);let o,n,a,i,l,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{l=e}));function _(){if(c)return d=!0,u(void 0);c=!0;return J(r,{_chunkSteps:e=>{p((()=>{d=!1;const t=e,r=e;f||cr(a._readableStreamController,t),b||cr(i._readableStreamController,r),c=!1,d&&_()}))},_closeSteps:()=>{c=!1,f||ur(a._readableStreamController),b||ur(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{c=!1}}),u(void 0)}function y(t){if(f=!0,o=t,b){const t=ue([o,n]),r=Er(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=ue([o,n]),r=Er(e,t);l(r)}return h}function g(){}return a=Rr(g,_,y),i=Rr(g,_,S),m(r._closedPromise,(e=>(dr(a._readableStreamController,e),dr(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function pr(e){return r(o=e)&&void 0!==o.getReader?function(e){let o;function n(){let t;try{t=e.read()}catch(e){return c(e)}return h(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)ur(o._readableStreamController);else{const t=e.value;cr(o._readableStreamController,t)}}))}function a(t){try{return u(e.cancel(t))}catch(e){return c(e)}}return o=Rr(t,n,a,0),o}(e.getReader()):function(e){let o;const n=_e(e,"async");function a(){let e;try{e=function(e){const t=y(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return c(e)}return h(u(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)ur(o._readableStreamController);else{const t=function(e){return e.value}(e);cr(o._readableStreamController,t)}}))}function i(e){const t=n.iterator;let o,a;try{o=me(t,"return")}catch(e){return c(e)}if(void 0===o)return u(void 0);try{a=y(o,t,[e])}catch(e){return c(e)}return h(u(a),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return o=Rr(t,a,i,0),o}(e);var o}function yr(e,t,r){return L(e,r),r=>S(e,t,[r])}function Sr(e,t,r){return L(e,r),r=>S(e,t,[r])}function gr(e,t,r){return L(e,r),r=>y(e,t,[r])}function vr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function wr(e,t){z(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=st(t,"Second parameter"),o=function(e,t){z(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:Q(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:yr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Sr(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:gr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:vr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(Cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>u(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ue(e,o,n,a,i,r,l)}(this,o,it(r,0))}else{const e=lt(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>u(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0),mr(e,n,a,i,l,r,o)}(this,o,it(r,1),e)}}get locked(){if(!Pr(this))throw Or("locked");return qr(this)}cancel(e=void 0){return Pr(this)?qr(this)?c(new TypeError("Cannot cancel a stream that already has a reader")):Er(this,e):c(Or("cancel"))}getReader(e=void 0){if(!Pr(this))throw Or("getReader");return void 0===function(e,t){z(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Je(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?N(this):Ke(this)}pipeThrough(e,t={}){if(!Pr(this))throw Or("pipeThrough");I(e,1,"pipeThrough");const r=function(e,t){z(e,t);const r=null==e?void 0:e.readable;$(r,"readable","ReadableWritablePair"),x(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return $(o,"writable","ReadableWritablePair"),mt(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=wr(t,"Second parameter");if(qr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(St(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return _(nr(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Pr(this))return c(Or("pipeTo"));if(void 0===e)return c("Parameter 1 is required in 'pipeTo'.");if(!yt(e))return c(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=wr(t,"Second parameter")}catch(e){return c(e)}return qr(this)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):St(e)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):nr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Pr(this))throw Or("tee");return ue(_r(this))}values(e=void 0){if(!Pr(this))throw Or("values");return function(e,t){const r=N(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){z(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[he](e){return this.values(e)}static from(e){return pr(e)}}function Rr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);Cr(a);return mr(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function Tr(e,t,r){const o=Object.create(ReadableStream.prototype);Cr(o);return Ue(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function Cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Pr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function qr(e){return void 0!==e._reader}function Er(e,r){if(e._disturbed=!0,"closed"===e._state)return u(void 0);if("errored"===e._state)return c(e._storedError);Wr(e);const o=e._reader;if(void 0!==o&&rt(o)){const e=o._readIntoRequests;o._readIntoRequests=new g,e.forEach((e=>{e._closeSteps(void 0)}))}return h(e._readableStreamController[R](r),t)}function Wr(e){e._state="closed";const t=e._reader;if(void 0!==t&&(k(t),X(t))){const e=t._readRequests;t._readRequests=new g,e.forEach((e=>{e._closeSteps()}))}}function Br(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),X(r)?K(r,t):nt(r,t))}function Or(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function jr(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark;return $(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:M(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.from,"from"),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStream.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(ReadableStream.prototype,he,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const kr=e=>e.byteLength;n(kr,"size");class ByteLengthQueuingStrategy{constructor(e){I(e,1,"ByteLengthQueuingStrategy"),e=jr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Dr(this))throw Ar("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Dr(this))throw Ar("size");return kr}}function Ar(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Dr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const zr=()=>1;n(zr,"size");class CountQueuingStrategy{constructor(e){I(e,1,"CountQueuingStrategy"),e=jr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Fr(this))throw Lr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Fr(this))throw Lr("size");return zr}}function Lr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Fr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Ir(e,t,r){return L(e,r),r=>S(e,t,[r])}function $r(e,t,r){return L(e,r),r=>y(e,t,[r])}function Mr(e,t,r){return L(e,r),(r,o)=>S(e,t,[r,o])}function Yr(e,t,r){return L(e,r),r=>S(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=st(t,"Second parameter"),n=st(r,"Third parameter"),a=function(e,t){z(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Yr(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:Ir(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:$r(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Mr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=it(n,0),l=lt(n),d=it(o,1),b=lt(o);let m;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return h(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Jr(r,t)}))}return Jr(r,t)}(e,t)}function u(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Gr(r),f(n,(()=>("errored"===o._state?eo(r,o._storedError):(dr(o._readableStreamController,t),Zr(r)),null)),(e=>(dr(o._readableStreamController,e),eo(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=s(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return Gr(t),f(o,(()=>("errored"===r._state?eo(t,r._storedError):(ur(r._readableStreamController),Zr(t)),null)),(e=>(dr(r._readableStreamController,e),eo(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return Vr(e,!1),e._backpressureChangePromise}(e)}function b(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Gr(r),f(n,(()=>("errored"===o._state?eo(r,o._storedError):($t(o._writableStreamController,t),Hr(e),Zr(r)),null)),(t=>($t(o._writableStreamController,t),Hr(e),eo(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return pt(i),zt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,u,r,o),e._readable=Rr(i,d,b,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Vr(e,!0),e._transformStreamController=void 0}(this,s((e=>{m=e})),d,b,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return Xr(r,e),u(void 0)}catch(e){return c(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>u(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?m(a.start(this._transformStreamController)):m(void 0)}get readable(){if(!Qr(this))throw to("readable");return this._readable}get writable(){if(!Qr(this))throw to("writable");return this._writable}}function Qr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function xr(e,t){dr(e._readable._readableStreamController,t),Nr(e,t)}function Nr(e,t){Gr(e._transformStreamController),$t(e._writable._writableStreamController,t),Hr(e)}function Hr(e){e._backpressure&&Vr(e,!1)}function Vr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStream.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ur(this))throw Kr("desiredSize");return fr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Ur(this))throw Kr("enqueue");Xr(this,e)}error(e=void 0){if(!Ur(this))throw Kr("error");var t;t=e,xr(this._controlledTransformStream,t)}terminate(){if(!Ur(this))throw Kr("terminate");!function(e){const t=e._controlledTransformStream;ur(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Nr(t,r)}(this)}}function Ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function Gr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function Xr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!br(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{cr(o,t)}catch(e){throw Nr(r,e),r._readable._storedError}const n=function(e){return!lr(e)}(o);n!==r._backpressure&&Vr(r,!0)}function Jr(e,t){return h(e._transformAlgorithm(t),void 0,(t=>{throw xr(e._controlledTransformStream,t),t}))}function Kr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Zr(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function eo(e,t){void 0!==e._finishPromise_reject&&(_(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function to(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const ro={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==rr)for(const e in ro)Object.prototype.hasOwnProperty.call(ro,e)&&Object.defineProperty(rr,e,{value:ro[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es2018.min.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map new file mode 100644 index 0000000..2a68110 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.min.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","Symbol","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","defineProperties","enumerable","toStringTag","AsyncIteratorPrototype","getPrototypeOf","async","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","next","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","SymbolAsyncIterator","_c","asyncIterator","_b","for","GetIterator","hint","method","syncIteratorRecord","syncIterable","iterator","nextMethod","CreateAsyncFromSyncIterator","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;mQAAgBA,IAEhB,CCCM,SAAUC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CACzD,CAEO,MAAMC,EAUPH,EAEU,SAAAI,EAAgBC,EAAcC,GAC5C,IACEC,OAAOC,eAAeH,EAAI,OAAQ,CAChCI,MAAOH,EACPI,cAAc,GAEjB,CAAC,MAAAC,GAGD,CACH,CC1BA,MAAMC,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAwBJ,QAAQK,OAAOC,KAAKP,GAG5C,SAAUQ,EAAcC,GAI5B,OAAO,IAAIT,EAAgBS,EAC7B,CAGM,SAAUC,EAAuBb,GACrC,OAAOW,GAAWG,GAAWA,EAAQd,IACvC,CAGM,SAAUe,EAA+BC,GAC7C,OAAOR,EAAsBQ,EAC/B,UAEgBC,EACdC,EACAC,EACAC,GAGA,OAAOf,EAAoBgB,KAAKH,EAASC,EAAaC,EACxD,UAKgBE,EACdJ,EACAC,EACAC,GACAH,EACEA,EAAmBC,EAASC,EAAaC,QACzCG,EACA7B,EAEJ,CAEgB,SAAA8B,EAAmBN,EAAqBC,GACtDG,EAAYJ,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BACAW,gEACAc,wDAEAoO,oDACAK,0CAEAQ,gCACAwC,mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAM9R,KAAQ6e,GACbzrB,OAAOQ,UAAUgJ,eAAejI,KAAKkqB,GAAS7e,IAChD5M,OAAOC,eAAeye,GAAS9R,EAAM,CACnC1M,MAAOurB,GAAQ7e,GACfwS,UAAU,EACVjf,cAAc"} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs new file mode 100644 index 0000000..822ef39 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs @@ -0,0 +1,4745 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es2018.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map new file mode 100644 index 0000000..3d8bc87 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,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AAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;"} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js new file mode 100644 index 0000000..c93a0cb --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js @@ -0,0 +1,4838 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es6.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map new file mode 100644 index 0000000..1f20a0a --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB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QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js new file mode 100644 index 0000000..daaa95c --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.reject.bind(a);function s(e){return new a(e)}function u(e){return s((t=>t(e)))}function c(e){return l(e)}function d(e,t,r){return i.call(e,t,r)}function f(e,t,r){d(d(e,t,r),void 0,o)}function b(e,t){f(e,t)}function m(e,t){f(e,void 0,t)}function h(e,t,r){return d(e,t,r)}function _(e){d(e,void 0,o)}let p=e=>{if("function"==typeof queueMicrotask)p=queueMicrotask;else{const e=u(void 0);p=t=>d(e,t)}return p(e)};function y(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function S(e,t,r){try{return u(y(e,t,r))}catch(e){return c(e)}}class g{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=Symbol("[[AbortSteps]]"),w=Symbol("[[ErrorSteps]]"),R=Symbol("[[CancelSteps]]"),T=Symbol("[[PullSteps]]"),C=Symbol("[[ReleaseSteps]]");function P(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),k(e)}(e):O(e,t._storedError)}function q(e,t){return kr(e._ownerReadableStream,t)}function E(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){O(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function O(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function k(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const A=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function z(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function L(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function F(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function M(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!A(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return A(o)&&0!==o?o:0}function Q(e,t){if(!Or(e))throw new TypeError(`${t} is not a ReadableStream.`)}function N(e){return new ReadableStreamDefaultReader(e)}function H(e,t){e._reader._readRequests.push(t)}function V(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function U(e){return e._reader._readRequests.length}function G(e){const t=e._reader;return void 0!==t&&!!X(t)}class ReadableStreamDefaultReader{constructor(e){if(F(e,1,"ReadableStreamDefaultReader"),Q(e,"First parameter"),jr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new g}get closed(){return X(this)?this._closedPromise:c(Z("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(Z("cancel"))}read(){if(!X(this))return c(Z("read"));if(void 0===this._ownerReadableStream)return c(W("read from"));let e,t;const r=s(((r,o)=>{e=r,t=o}));return J(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw Z("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");K(e,t)}(this)}}function X(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function J(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[T](t)}function K(e,t){const r=e._readRequests;e._readRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}function ee(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function te(e){return this instanceof te?(this.v=e,this):new te(e)}function re(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,n=r.apply(e,t||[]),a=[];return o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o;function i(e){n[e]&&(o[e]=function(t){return new Promise((function(r,o){a.push([e,t,r,o])>1||l(e,t)}))})}function l(e,t){try{(r=n[e](t)).value instanceof te?Promise.resolve(r.value.v).then(s,u):c(a[0][2],r)}catch(e){c(a[0][3],e)}var r}function s(e){l("next",e)}function u(e){l("throw",e)}function c(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}function oe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=ee(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(r){t[r]=e[r]&&function(t){return new Promise((function(o,n){(function(e,t,r,o){Promise.resolve(o).then((function(t){e({value:t,done:r})}),t)})(o,n,(t=e[r](t)).done,t.value)}))}}}var ne,ae,ie;function le(e){return e.slice()}function se(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"function"==typeof SuppressedError&&SuppressedError;let ue=e=>(ue="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,ue(e)),ce=e=>(ce="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,ce(e));function de(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return se(n,0,e,t,o),n}function fe(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}function be(e){const t={[Symbol.iterator]:()=>e.iterator},r=function(){return re(this,arguments,(function*(){return yield te(yield te(yield*function(e){var t,r;return t={},o("next"),o("throw",(function(e){throw e})),o("return"),t[Symbol.iterator]=function(){return this},t;function o(o,n){t[o]=e[o]?function(t){return(r=!r)?{value:te(e[o](t)),done:!1}:n?n(t):t}:n}}(oe(t))))}))}();return{iterator:r,nextMethod:r.next,done:!1}}const me=null!==(ie=null!==(ne=Symbol.asyncIterator)&&void 0!==ne?ne:null===(ae=Symbol.for)||void 0===ae?void 0:ae.call(Symbol,"Symbol.asyncIterator"))&&void 0!==ie?ie:"@@asyncIterator";function he(e,t="sync",o){if(void 0===o)if("async"===t){if(void 0===(o=fe(e,me))){return be(he(e,"sync",fe(e,Symbol.iterator)))}}else o=fe(e,Symbol.iterator);if(void 0===o)throw new TypeError("The object is not iterable");const n=y(o,e,[]);if(!r(n))throw new TypeError("The iterator method must return an object");return{iterator:n,nextMethod:n.next,done:!1}}const _e={[me](){return this}};Object.defineProperty(_e,me,{enumerable:!1});class pe{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?h(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?h(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=s(((e,o)=>{t=e,r=o}));return J(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,p((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=q(t,e);return E(t),h(r,(()=>({value:e,done:!0})))}return E(t),u({value:e,done:!0})}}const ye={next(){return Se(this)?this._asyncIteratorImpl.next():c(ge("next"))},return(e){return Se(this)?this._asyncIteratorImpl.return(e):c(ge("return"))}};function Se(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof pe}catch(e){return!1}}function ge(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(ye,_e);const ve=Number.isNaN||function(e){return e!=e};function we(e){const t=de(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function Re(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Te(e,t,r){if("number"!=typeof(o=r)||ve(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function Ce(e){e._queue=new g,e._queueTotalSize=0}function Pe(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ee(this))throw et("view");return this._view}respond(e){if(!Ee(this))throw et("respond");if(F(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Ee(this))throw et("respondWithNewView");if(F(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ke(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!qe(this))throw tt("byobRequest");return Ge(this)}get desiredSize(){if(!qe(this))throw tt("desiredSize");return Xe(this)}close(){if(!qe(this))throw tt("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ne(this)}enqueue(e){if(!qe(this))throw tt("enqueue");if(F(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);He(this,e)}error(e=void 0){if(!qe(this))throw tt("error");Ve(this,e)}[R](e){Be(this),Ce(this);const t=this._cancelAlgorithm(e);return Qe(this),t}[T](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Ue(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}H(t,e),We(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new g,this._pendingPullIntos.push(e)}}}function qe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function Ee(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function We(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(G(t)&&U(t)>0)return!0;if(it(t)&&at(t)>0)return!0;const r=Xe(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,We(e)),null)),(t=>(Ve(e,t),null)))}function Be(e){Fe(e),e._pendingPullIntos=new g}function Oe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=je(t);"default"===t.readerType?V(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function je(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ke(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Ae(e,t,r,o){let n;try{n=de(t,r,r+o)}catch(t){throw Ve(e,t),t}ke(e,n,0,o)}function De(e,t){t.bytesFilled>0&&Ae(e,t.buffer,t.byteOffset,t.bytesFilled),xe(e)}function ze(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;se(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Ie(e,o,t),n-=o}return a}function Ie(e,t,r){r.bytesFilled+=t}function Le(e){0===e._queueTotalSize&&e._closeRequested?(Qe(e),Ar(e._controlledReadableByteStream)):We(e)}function Fe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function $e(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ze(e,t)&&(xe(e),Oe(e._controlledReadableByteStream,t))}}function Me(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return Pe(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=ue(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void nt(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(ze(e,d)){const t=je(d);return Le(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ve(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),nt(n,o),We(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Ye(e,t){const r=e._pendingPullIntos.peek();Fe(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&xe(e);const r=e._controlledReadableByteStream;if(it(r))for(;at(r)>0;)Oe(r,xe(e))}(e,r):function(e,t,r){if(Ie(0,t,r),"none"===r.readerType)return De(e,r),void $e(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;Ae(e,r.buffer,t-o,o)}r.bytesFilled-=o,Oe(e._controlledReadableByteStream,r),$e(e)}(e,t,r),We(e)}function xe(e){return e._pendingPullIntos.shift()}function Qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ne(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ve(e,t),t}}Qe(e),Ar(t)}}function He(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(ce(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=ue(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(ce(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Fe(e),t.buffer=ue(t.buffer),"none"===t.readerType&&De(e,t)}if(G(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Ue(e,t._readRequests.shift())}}(e),0===U(r))ke(e,i,n,a);else{e._pendingPullIntos.length>0&&xe(e);V(r,new Uint8Array(i,n,a),!1)}else it(r)?(ke(e,i,n,a),$e(e)):ke(e,i,n,a);We(e)}function Ve(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Be(e),Ce(e),Qe(e),Dr(r,t))}function Ue(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Le(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function Ge(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Xe(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=ue(r.buffer),Ye(e,t)}function Ke(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=ue(t.buffer),Ye(e,o)}function Ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,Ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new g,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,We(t),null)),(e=>(Ve(t,e),null)))}function et(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function tt(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function rt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function ot(e){return new ReadableStreamBYOBReader(e)}function nt(e,t){e._reader._readIntoRequests.push(t)}function at(e){return e._reader._readIntoRequests.length}function it(e){const t=e._reader;return void 0!==t&&!!lt(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(F(e,1,"ReadableStreamBYOBReader"),Q(e,"First parameter"),jr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!qe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");P(this,e),this._readIntoRequests=new g}get closed(){return lt(this)?this._closedPromise:c(ct("closed"))}cancel(e=void 0){return lt(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(ct("cancel"))}read(e,t={}){if(!lt(this))return c(ct("read"));if(!ArrayBuffer.isView(e))return c(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return c(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return c(new TypeError("view's buffer must have non-zero byteLength"));if(ce(e.buffer))return c(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return z(e,t),{min:x(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return c(e)}const o=r.min;if(0===o)return c(new TypeError("options.min must be greater than 0"));if(function(e){return Pe(e.constructor)}(e)){if(o>e.byteLength)return c(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return c(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return c(W("read from"));let n,a;const i=s(((e,t)=>{n=e,a=t}));return st(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!lt(this))throw ct("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");ut(e,t)}(this)}}function lt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function st(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):Me(n._readableStreamController,t,r,o)}function ut(e,t){const r=e._readIntoRequests;e._readIntoRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function ct(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function dt(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ve(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function ft(e){const{size:t}=e;return t||(()=>1)}function bt(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:M(r),size:void 0===o?void 0:mt(o,`${t} has member 'size' that`)}}function mt(e,t){return I(e,t),t=>M(e(t))}function ht(e,t,r){return I(e,r),r=>S(e,t,[r])}function _t(e,t,r){return I(e,r),()=>S(e,t,[])}function pt(e,t,r){return I(e,r),r=>y(e,t,[r])}function yt(e,t,r){return I(e,r),(r,o)=>S(e,t,[r,o])}function St(e,t){if(!Rt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const gt="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=bt(t,"Second parameter"),o=function(e,t){z(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:ht(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:_t(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:pt(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:yt(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");wt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=ft(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>u(void 0);l=void 0!==t.close?()=>t.close():()=>u(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>u(void 0);Mt(e,n,a,i,l,s,r,o)}(this,o,dt(r,1),n)}get locked(){if(!Rt(this))throw Ut("locked");return Tt(this)}abort(e=void 0){return Rt(this)?Tt(this)?c(new TypeError("Cannot abort a stream that already has a writer")):Ct(this,e):c(Ut("abort"))}close(){return Rt(this)?Tt(this)?c(new TypeError("Cannot close a stream that already has a writer")):Bt(this)?c(new TypeError("Cannot close an already-closing stream")):Pt(this):c(Ut("close"))}getWriter(){if(!Rt(this))throw Ut("getWriter");return vt(this)}}function vt(e){return new WritableStreamDefaultWriter(e)}function wt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new g,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Rt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Tt(e){return void 0!==e._writer}function Ct(e,t){var r;if("closed"===e._state||"errored"===e._state)return u(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return u(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=s(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||Et(e,t),a}function Pt(e){const t=e._state;if("closed"===t||"errored"===t)return c(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=s(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&ir(o),Te(n=e._writableStreamController,Ft,0),Qt(n),r}function qt(e,t){"writable"!==e._state?Wt(e):Et(e,t)}function Et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&zt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Wt(e)}function Wt(e){e._state="errored",e._writableStreamController[w]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new g,void 0===e._pendingAbortRequest)return void Ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Ot(e);f(e._writableStreamController[v](r._reason),(()=>(r._resolve(),Ot(e),null)),(t=>(r._reject(t),Ot(e),null)))}function Bt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&er(t,e._storedError)}function jt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){rr(e)}(r):ir(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStream.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(F(e,1,"WritableStreamDefaultWriter"),St(e,"First parameter"),Tt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!Bt(e)&&e._backpressure?rr(this):nr(this),Kt(this);else if("erroring"===t)or(this,e._storedError),Kt(this);else if("closed"===t)nr(this),Kt(r=this),tr(r);else{const t=e._storedError;or(this,t),Zt(this,t)}var r}get closed(){return kt(this)?this._closedPromise:c(Xt("closed"))}get desiredSize(){if(!kt(this))throw Xt("desiredSize");if(void 0===this._ownerWritableStream)throw Jt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return xt(t._writableStreamController)}(this)}get ready(){return kt(this)?this._readyPromise:c(Xt("ready"))}abort(e=void 0){return kt(this)?void 0===this._ownerWritableStream?c(Jt("abort")):function(e,t){return Ct(e._ownerWritableStream,t)}(this,e):c(Xt("abort"))}close(){if(!kt(this))return c(Xt("close"));const e=this._ownerWritableStream;return void 0===e?c(Jt("close")):Bt(e)?c(new TypeError("Cannot close an already-closing stream")):At(this)}releaseLock(){if(!kt(this))throw Xt("releaseLock");void 0!==this._ownerWritableStream&&It(this)}write(e=void 0){return kt(this)?void 0===this._ownerWritableStream?c(Jt("write to")):Lt(this,e):c(Xt("write"))}}function kt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function At(e){return Pt(e._ownerWritableStream)}function Dt(e,t){"pending"===e._closedPromiseState?er(e,t):function(e,t){Zt(e,t)}(e,t)}function zt(e,t){"pending"===e._readyPromiseState?ar(e,t):function(e,t){or(e,t)}(e,t)}function It(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zt(e,r),Dt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Lt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Nt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return c(Jt("write to"));const a=r._state;if("errored"===a)return c(r._storedError);if(Bt(r)||"closed"===a)return c(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return c(r._storedError);const i=function(e){return s(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{Te(e,t,r)}catch(t){return void Nt(e,t)}const o=e._controlledWritableStream;if(!Bt(o)&&"writable"===o._state){jt(o,Ht(e))}Qt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Ft={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!$t(this))throw Gt("abortReason");return this._abortReason}get signal(){if(!$t(this))throw Gt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!$t(this))throw Gt("error");"writable"===this._controlledWritableStream._state&&Vt(this,e)}[v](e){const t=this._abortAlgorithm(e);return Yt(this),t}[w](){Ce(this)}}function $t(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function Mt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,Ce(t),t._abortReason=void 0,t._abortController=function(){if(gt)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Ht(t);jt(e,s);f(u(r()),(()=>(t._started=!0,Qt(t),null)),(r=>(t._started=!0,qt(e,r),null)))}function Yt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function xt(e){return e._strategyHWM-e._queueTotalSize}function Qt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Wt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Ft?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),Re(e);const r=e._closeAlgorithm();Yt(e),f(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&tr(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),qt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);f(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(Re(e),!Bt(r)&&"writable"===t){const t=Ht(e);jt(r,t)}return Qt(e),null}),(t=>("writable"===r._state&&Yt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,qt(e,t)}(r,t),null)))}(e,r)}function Nt(e,t){"writable"===e._controlledWritableStream._state&&Vt(e,t)}function Ht(e){return xt(e)<=0}function Vt(e,t){const r=e._controlledWritableStream;Yt(e),Et(r,t)}function Ut(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Gt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Xt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Jt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Kt(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Zt(e,t){Kt(e),er(e,t)}function er(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function tr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function rr(e){e._readyPromise=s(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function or(e,t){rr(e),ar(e,t)}function nr(e){rr(e),ir(e)}function ar(e,t){void 0!==e._readyPromise_reject&&(_(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function ir(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const sr=function(){const e=null==lr?void 0:lr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return n(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function ur(e,r,o,n,a,i){const l=N(e),h=vt(r);e._disturbed=!0;let p=!1,y=u(void 0);return s(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const t=void 0!==i.reason?i.reason:new sr("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===r._state?Ct(r,t):u(void 0))),a||o.push((()=>"readable"===e._state?kr(e,t):u(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,t)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?W(!0,e):q((()=>Ct(r,e)),!0,e),null))),P(r,h._closedPromise,(t=>(a?W(!0,t):q((()=>kr(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?W():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return Bt(t)||"closed"===r?u(void 0):"errored"===r?c(t._storedError):At(e)}(h))),null),"closed"===w._state?T():b(R,T),Bt(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):q((()=>kr(e,t)),!0,t)}function C(){const e=y;return d(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,t,o){function n(){return f(e(),(()=>B(t,o)),(e=>B(!0,e))),null}p||(p=!0,"writable"!==r._state||Bt(r)?n():b(C(),n))}function W(e,t){p||(p=!0,"writable"!==r._state||Bt(r)?B(e,t):b(C(),(()=>B(e,t))))}function B(e,t){return It(h),E(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}_(s(((e,r)=>{!function o(n){n?e():d(p?u(!0):d(h._readyPromise,(()=>s(((e,r)=>{J(l,{_chunkSteps:r=>{y=d(Lt(h,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),o,r)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!cr(this))throw gr("desiredSize");return pr(this)}close(){if(!cr(this))throw gr("close");if(!yr(this))throw new TypeError("The stream is not in a state that permits close");mr(this)}enqueue(e=void 0){if(!cr(this))throw gr("enqueue");if(!yr(this))throw new TypeError("The stream is not in a state that permits enqueue");return hr(this,e)}error(e=void 0){if(!cr(this))throw gr("error");_r(this,e)}[R](e){Ce(this);const t=this._cancelAlgorithm(e);return br(this),t}[T](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=Re(this);this._closeRequested&&0===this._queue.length?(br(this),Ar(t)):dr(this),e._chunkSteps(r)}else H(t,e),dr(this)}[C](){}}function cr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function dr(e){if(!fr(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,dr(e)),null)),(t=>(_r(e,t),null)))}function fr(e){const t=e._controlledReadableStream;if(!yr(e))return!1;if(!e._started)return!1;if(jr(t)&&U(t)>0)return!0;return pr(e)>0}function br(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function mr(e){if(!yr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(br(e),Ar(t))}function hr(e,t){if(!yr(e))return;const r=e._controlledReadableStream;if(jr(r)&&U(r)>0)V(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw _r(e,t),t}try{Te(e,t,r)}catch(t){throw _r(e,t),t}}dr(e)}function _r(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(Ce(e),br(e),Dr(r,t))}function pr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function yr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Sr(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,Ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,dr(t),null)),(e=>(_r(t,e),null)))}function gr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function vr(e,t){return qe(e._readableStreamController)?function(e){let t,r,o,n,a,i=N(e),l=!1,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Ve(o._readableStreamController,t),Ve(n._readableStreamController,t),f&&b||a(void 0)),null)))}function y(){lt(i)&&(E(i),i=N(e),_(i));J(i,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=we(t)}catch(t){return Ve(o._readableStreamController,t),Ve(n._readableStreamController,t),void a(kr(e,t))}f||He(o._readableStreamController,r),b||He(n._readableStreamController,i),l=!1,c?g():d&&v()}))},_closeSteps:()=>{l=!1,f||Ne(o._readableStreamController),b||Ne(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){X(i)&&(E(i),i=ot(e),_(i));const s=r?n:o,u=r?o:n;st(i,t,1,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const o=r?b:f;if(r?f:b)o||Ke(s._readableStreamController,t);else{let r;try{r=we(t)}catch(t){return Ve(s._readableStreamController,t),Ve(u._readableStreamController,t),void a(kr(e,t))}o||Ke(s._readableStreamController,t),He(u._readableStreamController,r)}l=!1,c?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ne(s._readableStreamController),o||Ne(u._readableStreamController),void 0!==e&&(t||Ke(s._readableStreamController,e),!o&&u._readableStreamController._pendingPullIntos.length>0&&Je(u._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return c=!0,u(void 0);l=!0;const e=Ge(o._readableStreamController);return null===e?y():S(e._view,!1),u(void 0)}function v(){if(l)return d=!0,u(void 0);l=!0;const e=Ge(n._readableStreamController);return null===e?y():S(e._view,!0),u(void 0)}function w(o){if(f=!0,t=o,b){const o=le([t,r]),n=kr(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=le([t,r]),n=kr(e,o);a(n)}return h}function T(){}return o=Wr(T,g,w),n=Wr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=N(e);let o,n,a,i,l,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{l=e}));function _(){if(c)return d=!0,u(void 0);c=!0;return J(r,{_chunkSteps:e=>{p((()=>{d=!1;const t=e,r=e;f||hr(a._readableStreamController,t),b||hr(i._readableStreamController,r),c=!1,d&&_()}))},_closeSteps:()=>{c=!1,f||mr(a._readableStreamController),b||mr(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{c=!1}}),u(void 0)}function y(t){if(f=!0,o=t,b){const t=le([o,n]),r=kr(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=le([o,n]),r=kr(e,t);l(r)}return h}function g(){}return a=Er(g,_,y),i=Er(g,_,S),m(r._closedPromise,(e=>(_r(a._readableStreamController,e),_r(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function wr(e){return r(o=e)&&void 0!==o.getReader?function(e){let o;function n(){let t;try{t=e.read()}catch(e){return c(e)}return h(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)mr(o._readableStreamController);else{const t=e.value;hr(o._readableStreamController,t)}}))}function a(t){try{return u(e.cancel(t))}catch(e){return c(e)}}return o=Er(t,n,a,0),o}(e.getReader()):function(e){let o;const n=he(e,"async");function a(){let e;try{e=function(e){const t=y(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return c(e)}return h(u(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)mr(o._readableStreamController);else{const t=function(e){return e.value}(e);hr(o._readableStreamController,t)}}))}function i(e){const t=n.iterator;let o,a;try{o=fe(t,"return")}catch(e){return c(e)}if(void 0===o)return u(void 0);try{a=y(o,t,[e])}catch(e){return c(e)}return h(u(a),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return o=Er(t,a,i,0),o}(e);var o}function Rr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Tr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Cr(e,t,r){return I(e,r),r=>y(e,t,[r])}function Pr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function qr(e,t){z(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=bt(t,"Second parameter"),o=function(e,t){z(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:Rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Tr(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Cr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Pr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(Br(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>u(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ze(e,o,n,a,i,r,l)}(this,o,dt(r,0))}else{const e=ft(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>u(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0),Sr(e,n,a,i,l,r,o)}(this,o,dt(r,1),e)}}get locked(){if(!Or(this))throw zr("locked");return jr(this)}cancel(e=void 0){return Or(this)?jr(this)?c(new TypeError("Cannot cancel a stream that already has a reader")):kr(this,e):c(zr("cancel"))}getReader(e=void 0){if(!Or(this))throw zr("getReader");return void 0===function(e,t){z(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:rt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?N(this):ot(this)}pipeThrough(e,t={}){if(!Or(this))throw zr("pipeThrough");F(e,1,"pipeThrough");const r=function(e,t){z(e,t);const r=null==e?void 0:e.readable;$(r,"readable","ReadableWritablePair"),Q(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return $(o,"writable","ReadableWritablePair"),St(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=qr(t,"Second parameter");if(jr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Tt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return _(ur(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Or(this))return c(zr("pipeTo"));if(void 0===e)return c("Parameter 1 is required in 'pipeTo'.");if(!Rt(e))return c(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=qr(t,"Second parameter")}catch(e){return c(e)}return jr(this)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Tt(e)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):ur(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Or(this))throw zr("tee");return le(vr(this))}values(e=void 0){if(!Or(this))throw zr("values");return function(e,t){const r=N(e),o=new pe(r,t),n=Object.create(ye);return n._asyncIteratorImpl=o,n}(this,function(e,t){z(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[me](e){return this.values(e)}static from(e){return wr(e)}}function Er(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);Br(a);return Sr(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function Wr(e,t,r){const o=Object.create(ReadableStream.prototype);Br(o);return Ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function Br(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Or(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function jr(e){return void 0!==e._reader}function kr(e,r){if(e._disturbed=!0,"closed"===e._state)return u(void 0);if("errored"===e._state)return c(e._storedError);Ar(e);const o=e._reader;if(void 0!==o&<(o)){const e=o._readIntoRequests;o._readIntoRequests=new g,e.forEach((e=>{e._closeSteps(void 0)}))}return h(e._readableStreamController[R](r),t)}function Ar(e){e._state="closed";const t=e._reader;if(void 0!==t&&(k(t),X(t))){const e=t._readRequests;t._readRequests=new g,e.forEach((e=>{e._closeSteps()}))}}function Dr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),X(r)?K(r,t):ut(r,t))}function zr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Ir(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark;return $(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:M(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.from,"from"),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStream.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(ReadableStream.prototype,me,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const Lr=e=>e.byteLength;n(Lr,"size");class ByteLengthQueuingStrategy{constructor(e){F(e,1,"ByteLengthQueuingStrategy"),e=Ir(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!$r(this))throw Fr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!$r(this))throw Fr("size");return Lr}}function Fr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function $r(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Mr=()=>1;n(Mr,"size");class CountQueuingStrategy{constructor(e){F(e,1,"CountQueuingStrategy"),e=Ir(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!xr(this))throw Yr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!xr(this))throw Yr("size");return Mr}}function Yr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function xr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Qr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Nr(e,t,r){return I(e,r),r=>y(e,t,[r])}function Hr(e,t,r){return I(e,r),(r,o)=>S(e,t,[r,o])}function Vr(e,t,r){return I(e,r),r=>S(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=bt(t,"Second parameter"),n=bt(r,"Third parameter"),a=function(e,t){z(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Vr(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:Qr(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:Nr(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Hr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=dt(n,0),l=ft(n),d=dt(o,1),b=ft(o);let m;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return h(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return ro(r,t)}))}return ro(r,t)}(e,t)}function u(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return eo(r),f(n,(()=>("errored"===o._state?ao(r,o._storedError):(_r(o._readableStreamController,t),no(r)),null)),(e=>(_r(o._readableStreamController,e),ao(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=s(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return eo(t),f(o,(()=>("errored"===r._state?ao(t,r._storedError):(mr(r._readableStreamController),no(t)),null)),(e=>(_r(r._readableStreamController,e),ao(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return Kr(e,!1),e._backpressureChangePromise}(e)}function b(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return eo(r),f(n,(()=>("errored"===o._state?ao(r,o._storedError):(Nt(o._writableStreamController,t),Jr(e),no(r)),null)),(t=>(Nt(o._writableStreamController,t),Jr(e),ao(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return wt(i),Mt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,u,r,o),e._readable=Er(i,d,b,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Kr(e,!0),e._transformStreamController=void 0}(this,s((e=>{m=e})),d,b,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return to(r,e),u(void 0)}catch(e){return c(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>u(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?m(a.start(this._transformStreamController)):m(void 0)}get readable(){if(!Ur(this))throw io("readable");return this._readable}get writable(){if(!Ur(this))throw io("writable");return this._writable}}function Ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Gr(e,t){_r(e._readable._readableStreamController,t),Xr(e,t)}function Xr(e,t){eo(e._transformStreamController),Nt(e._writable._writableStreamController,t),Jr(e)}function Jr(e){e._backpressure&&Kr(e,!1)}function Kr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStream.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Zr(this))throw oo("desiredSize");return pr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Zr(this))throw oo("enqueue");to(this,e)}error(e=void 0){if(!Zr(this))throw oo("error");var t;t=e,Gr(this._controlledTransformStream,t)}terminate(){if(!Zr(this))throw oo("terminate");!function(e){const t=e._controlledTransformStream;mr(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Xr(t,r)}(this)}}function Zr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function eo(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function to(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!yr(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{hr(o,t)}catch(e){throw Xr(r,e),r._readable._storedError}const n=function(e){return!fr(e)}(o);n!==r._backpressure&&Kr(r,!0)}function ro(e,t){return h(e._transformAlgorithm(t),void 0,(t=>{throw Gr(e._controlledTransformStream,t),t}))}function oo(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function no(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function ao(e,t){void 0!==e._finishPromise_reject&&(_(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function io(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const lo={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==lr)for(const e in lo)Object.prototype.hasOwnProperty.call(lo,e)&&Object.defineProperty(lr,e,{value:lo[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es6.min.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map new file mode 100644 index 0000000..8f6055c --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.min.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","Symbol","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","__values","o","s","iterator","m","next","__await","__asyncGenerator","thisArg","_arguments","generator","asyncIterator","g","q","verb","n","a","b","resume","r","fulfill","settle","f","__asyncValues","d","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","defineProperties","enumerable","toStringTag","SuppressedError","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","CreateAsyncFromSyncIterator","syncIteratorRecord","syncIterable","p","__asyncDelegator","nextMethod","SymbolAsyncIterator","_c","_b","for","GetIterator","hint","method","AsyncIteratorPrototype","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"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mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAMhT,KAAQ+f,GACb9sB,OAAOQ,UAAUgJ,eAAejI,KAAKurB,GAAS/f,IAChD/M,OAAOC,eAAe8f,GAAShT,EAAM,CACnC7M,MAAO4sB,GAAQ/f,GACf0T,UAAU,EACVtgB,cAAc","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs new file mode 100644 index 0000000..9c3f00f --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs @@ -0,0 +1,4818 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } +}; +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es6.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map new file mode 100644 index 0000000..d37f8bc --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAA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Y,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;ACzoBA,MAAM,OAAO,GAAG;IACd,cAAc;IACd,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;IAC3B,wBAAwB;IAExB,cAAc;IACd,+BAA+B;IAC/B,2BAA2B;IAE3B,yBAAyB;IACzB,oBAAoB;IAEpB,eAAe;IACf,gCAAgC;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js new file mode 100644 index 0000000..a4ebd70 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js @@ -0,0 +1,5011 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + var _a$1, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + var _a; + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + var exports$1 = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (var prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js.map new file mode 100644 index 0000000..d4aaa73 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ICL5D;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;AA4GA;IACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;IAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,C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AAA,yBAAyB,EAAA,yBAAA;IACzB,IAAA,2BAA2B,EAAA,2BAAA;IAC3B,IAAA,wBAAwB,EAAA,wBAAA;IAExB,IAAA,cAAc,EAAA,cAAA;IACd,IAAA,+BAA+B,EAAA,+BAAA;IAC/B,IAAA,2BAA2B,EAAA,2BAAA;IAE3B,IAAA,yBAAyB,EAAA,yBAAA;IACzB,IAAA,oBAAoB,EAAA,oBAAA;IAEpB,IAAA,eAAe,EAAA,eAAA;IACf,IAAA,gCAAgC,EAAA,gCAAA;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,IAAA,KAAK,IAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js new file mode 100644 index 0000000..9dd9212 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function t(e,r){var t,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function u(u){return function(l){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(i=0)),i;)try{if(t=1,n&&(o=2&u[0]?n.return:u[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,u[1])).done)return o;switch(n=0,o&&(u=[2&u[0],o.value]),u[0]){case 0:case 1:o=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,n=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==u[0]&&2!==u[0])){i=0;continue}if(3===u[0]&&(!o||u[1]>o[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(e){return this instanceof o?(this.v=e,this):new o(e)}function a(e,r,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,a=t.apply(e,r||[]),i=[];return n={},u("next"),u("throw"),u("return"),n[Symbol.asyncIterator]=function(){return this},n;function u(e){a[e]&&(n[e]=function(r){return new Promise((function(t,n){i.push([e,r,t,n])>1||l(e,r)}))})}function l(e,r){try{(t=a[e](r)).value instanceof o?Promise.resolve(t.value.v).then(s,c):f(i[0][2],t)}catch(e){f(i[0][3],e)}var t}function s(e){l("next",e)}function c(e){l("throw",e)}function f(e,r){e(r),i.shift(),i.length&&l(i[0][0],i[0][1])}}function i(e){var r,t;return r={},n("next"),n("throw",(function(e){throw e})),n("return"),r[Symbol.iterator]=function(){return this},r;function n(n,a){r[n]=e[n]?function(r){return(t=!t)?{value:o(e[n](r)),done:!1}:a?a(r):r}:a}}function u(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,t=e[Symbol.asyncIterator];return t?t.call(e):(e=n(e),r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r);function o(t){r[t]=e[t]&&function(r){return new Promise((function(n,o){(function(e,r,t,n){Promise.resolve(n).then((function(r){e({value:r,done:t})}),r)})(n,o,(r=e[t](r)).done,r.value)}))}}}function l(){}function s(e){return"object"==typeof e&&null!==e||"function"==typeof e}"function"==typeof SuppressedError&&SuppressedError;var c=l;function f(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var d=Promise,b=Promise.prototype.then,p=Promise.reject.bind(d);function h(e){return new d(e)}function m(e){return h((function(r){return r(e)}))}function _(e){return p(e)}function y(e,r,t){return b.call(e,r,t)}function v(e,r,t){y(y(e,r,t),void 0,c)}function g(e,r){v(e,r)}function S(e,r){v(e,void 0,r)}function w(e,r,t){return y(e,r,t)}function R(e){y(e,void 0,c)}var T=function(e){if("function"==typeof queueMicrotask)T=queueMicrotask;else{var r=m(void 0);T=function(e){return y(r,e)}}return T(e)};function P(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function C(e,r,t){try{return m(P(e,r,t))}catch(e){return _(e)}}var q=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),E=r("[[AbortSteps]]"),O=r("[[ErrorSteps]]"),W=r("[[CancelSteps]]"),j=r("[[PullSteps]]"),B=r("[[ReleaseSteps]]");function k(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?D(e):"closed"===r._state?function(e){D(e),M(e)}(e):L(e,r._storedError)}function A(e,r){return Vt(e._ownerReadableStream,r)}function z(e){var r=e._ownerReadableStream;"readable"===r._state?F(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){L(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[B](),r._reader=void 0,e._ownerReadableStream=void 0}function I(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function D(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function L(e,r){D(e),F(e,r)}function F(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function M(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var x=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Y=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Q(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function N(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function H(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function V(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function U(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function G(e){return Number(e)}function X(e){return 0===e?0:e}function J(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=X(n),!x(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return X(Y(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return x(n)&&0!==n?n:0}function K(e,r){if(!Nt(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function Z(e){return new ie(e)}function $(e,r){e._reader._readRequests.push(r)}function ee(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function re(e){return e._reader._readRequests.length}function te(e){var r=e._reader;return void 0!==r&&!!ue(r)}var ne,oe,ae,ie=function(){function ReadableStreamDefaultReader(e){if(V(e,1,"ReadableStreamDefaultReader"),K(e,"First parameter"),Ht(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");k(this,e),this._readRequests=new q}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ue(this)?this._closedPromise:_(ce("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ue(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(ce("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ue(this))return _(ce("read"));if(void 0===this._ownerReadableStream)return _(I("read from"));var e,r,t=h((function(t,n){e=t,r=n}));return le(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ue(this))throw ce("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");se(e,r)}(this)},ReadableStreamDefaultReader}();function ue(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ie)}function le(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[j](r)}function se(e,r){var t=e._readRequests;e._readRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function ce(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}function fe(e){return e.slice()}function de(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}Object.defineProperties(ie.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(ie.prototype.cancel,"cancel"),f(ie.prototype.read,"read"),f(ie.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(ie.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var be=function(e){return(be="function"==typeof e.transfer?function(e){return e.transfer()}:"function"==typeof structuredClone?function(e){return structuredClone(e,{transfer:[e]})}:function(e){return e})(e)},pe=function(e){return(pe="boolean"==typeof e.detached?function(e){return e.detached}:function(e){return 0===e.byteLength})(e)};function he(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return de(o,0,e,r,n),o}function me(e,r){var t=e[r];if(null!=t){if("function"!=typeof t)throw new TypeError("".concat(String(r)," is not a function"));return t}}var _e,ye=null!==(ae=null!==(ne=r.asyncIterator)&&void 0!==ne?ne:null===(oe=r.for)||void 0===oe?void 0:oe.call(r,"Symbol.asyncIterator"))&&void 0!==ae?ae:"@@asyncIterator";function ve(e,l,c){if(void 0===l&&(l="sync"),void 0===c)if("async"===l){if(void 0===(c=me(e,ye)))return function(e){var l,s=((l={})[r.iterator]=function(){return e.iterator},l),c=function(){return a(this,arguments,(function(){return t(this,(function(e){switch(e.label){case 0:return[5,n(i(u(s)))];case 1:case 2:return[4,o.apply(void 0,[e.sent()])];case 3:return[2,e.sent()]}}))}))}();return{iterator:c,nextMethod:c.next,done:!1}}(ve(e,"sync",me(e,r.iterator)))}else c=me(e,r.iterator);if(void 0===c)throw new TypeError("The object is not iterable");var f=P(c,e,[]);if(!s(f))throw new TypeError("The iterator method must return an object");return{iterator:f,nextMethod:f.next,done:!1}}var ge=((_e={})[ye]=function(){return this},_e);Object.defineProperty(ge,ye,{enumerable:!1});var Se=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?w(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r,t,n=this._reader,o=h((function(e,n){r=e,t=n}));return le(n,{_chunkSteps:function(t){e._ongoingPromise=void 0,T((function(){return r({value:t,done:!1})}))},_closeSteps:function(){e._ongoingPromise=void 0,e._isFinished=!0,z(n),r({value:void 0,done:!0})},_errorSteps:function(r){e._ongoingPromise=void 0,e._isFinished=!0,z(n),t(r)}}),o},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(!this._preventCancel){var t=A(r,e);return z(r),w(t,(function(){return{value:e,done:!0}}))}return z(r),m({value:e,done:!0})},e}(),we={next:function(){return Re(this)?this._asyncIteratorImpl.next():_(Te("next"))},return:function(e){return Re(this)?this._asyncIteratorImpl.return(e):_(Te("return"))}};function Re(e){if(!s(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof Se}catch(e){return!1}}function Te(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}Object.setPrototypeOf(we,ge);var Pe=Number.isNaN||function(e){return e!=e};function Ce(e){var r=he(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function qe(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function Ee(e,r,t){if("number"!=typeof(n=t)||Pe(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function Oe(e){e._queue=new q,e._queueTotalSize=0}function We(e){return e===DataView}var je=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!Ae(this))throw ir("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!Ae(this))throw ir("respond");if(V(e,1,"respond"),e=J(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(pe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");nr(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!Ae(this))throw ir("respondWithNewView");if(V(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(pe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");or(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(je.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),f(je.prototype.respond,"respond"),f(je.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof r.toStringTag&&Object.defineProperty(je.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var Be=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!ke(this))throw ur("byobRequest");return rr(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!ke(this))throw ur("desiredSize");return tr(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!ke(this))throw ur("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));Ke(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!ke(this))throw ur("enqueue");if(V(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));Ze(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!ke(this))throw ur("error");$e(this,e)},ReadableByteStreamController.prototype[W]=function(e){Ie(this),Oe(this);var r=this._cancelAlgorithm(e);return Je(this),r},ReadableByteStreamController.prototype[j]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)er(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}$(r,e),ze(this)}},ReadableByteStreamController.prototype[B]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new q,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function ke(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Be)}function Ae(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof je)}function ze(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(te(r)&&re(r)>0)return!0;if(dr(r)&&fr(r)>0)return!0;var t=tr(e);if(t>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ze(e)),null}),(function(r){return $e(e,r),null}))))}function Ie(e){He(e),e._pendingPullIntos=new q}function De(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=Le(r);"default"===r.readerType?ee(e,n,t):function(e,r,t){var n=e._reader,o=n._readIntoRequests.shift();t?o._closeSteps(r):o._chunkSteps(r)}(e,n,t)}function Le(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function Fe(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function Me(e,r,t,n){var o;try{o=he(r,t,t+n)}catch(r){throw $e(e,r),r}Fe(e,o,0,n)}function xe(e,r){r.bytesFilled>0&&Me(e,r.buffer,r.byteOffset,r.bytesFilled),Xe(e)}function Ye(e,r){var t=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),n=r.bytesFilled+t,o=t,a=!1,i=n-n%r.elementSize;i>=r.minimumFill&&(o=i-r.bytesFilled,a=!0);for(var u=e._queue;o>0;){var l=u.peek(),s=Math.min(o,l.byteLength),c=r.byteOffset+r.bytesFilled;de(r.buffer,c,l.buffer,l.byteOffset,s),l.byteLength===s?u.shift():(l.byteOffset+=s,l.byteLength-=s),e._queueTotalSize-=s,Qe(e,s,r),o-=s}return a}function Qe(e,r,t){t.bytesFilled+=r}function Ne(e){0===e._queueTotalSize&&e._closeRequested?(Je(e),Ut(e._controlledReadableByteStream)):ze(e)}function He(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ve(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Ye(e,r)&&(Xe(e),De(e._controlledReadableByteStream,r))}}function Ue(e,r,t,n){var o,a=e._controlledReadableByteStream,i=r.constructor,u=function(e){return We(e)?1:e.BYTES_PER_ELEMENT}(i),l=r.byteOffset,s=r.byteLength,c=t*u;try{o=be(r.buffer)}catch(b){return void n._errorSteps(b)}var f={buffer:o,bufferByteLength:o.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:c,elementSize:u,viewConstructor:i,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(f),void cr(a,n);if("closed"!==a._state){if(e._queueTotalSize>0){if(Ye(e,f)){var d=Le(f);return Ne(e),void n._chunkSteps(d)}if(e._closeRequested){var b=new TypeError("Insufficient bytes to fill elements in the given buffer");return $e(e,b),void n._errorSteps(b)}}e._pendingPullIntos.push(f),cr(a,n),ze(e)}else{var p=new i(f.buffer,f.byteOffset,0);n._closeSteps(p)}}function Ge(e,r){var t=e._pendingPullIntos.peek();He(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&Xe(e);var t=e._controlledReadableByteStream;if(dr(t))for(;fr(t)>0;)De(t,Xe(e))}(e,t):function(e,r,t){if(Qe(0,r,t),"none"===t.readerType)return xe(e,t),void Ve(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;Me(e,t.buffer,o-n,n)}t.bytesFilled-=n,De(e._controlledReadableByteStream,t),Ve(e)}}(e,r,t),ze(e)}function Xe(e){return e._pendingPullIntos.shift()}function Je(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ke(e){var r=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===r._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){var t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){var n=new TypeError("Insufficient bytes to fill elements in the given buffer");throw $e(e,n),n}}Je(e),Ut(r)}}function Ze(e,r){var t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state){var n=r.buffer,o=r.byteOffset,a=r.byteLength;if(pe(n))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");var i=be(n);if(e._pendingPullIntos.length>0){var u=e._pendingPullIntos.peek();if(pe(u.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");He(e),u.buffer=be(u.buffer),"none"===u.readerType&&xe(e,u)}if(te(t))if(function(e){for(var r=e._controlledReadableByteStream._reader;r._readRequests.length>0;){if(0===e._queueTotalSize)return;er(e,r._readRequests.shift())}}(e),0===re(t))Fe(e,i,o,a);else e._pendingPullIntos.length>0&&Xe(e),ee(t,new Uint8Array(i,o,a),!1);else dr(t)?(Fe(e,i,o,a),Ve(e)):Fe(e,i,o,a);ze(e)}}function $e(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(Ie(e),Oe(e),Je(e),Gt(t,r))}function er(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,Ne(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function rr(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(je.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}function tr(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function nr(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=be(t.buffer),Ge(e,r)}function or(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=be(r.buffer),Ge(e,n)}function ar(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,Oe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new q,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,ze(r),null}),(function(e){return $e(r,e),null}))}function ir(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function ur(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function lr(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function sr(e){return new br(e)}function cr(e,r){e._reader._readIntoRequests.push(r)}function fr(e){return e._reader._readIntoRequests.length}function dr(e){var r=e._reader;return void 0!==r&&!!pr(r)}Object.defineProperties(Be.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),f(Be.prototype.close,"close"),f(Be.prototype.enqueue,"enqueue"),f(Be.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Be.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var br=function(){function ReadableStreamBYOBReader(e){if(V(e,1,"ReadableStreamBYOBReader"),K(e,"First parameter"),Ht(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!ke(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");k(this,e),this._readIntoRequests=new q}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return pr(this)?this._closedPromise:_(_r("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),pr(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(_r("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e,r){if(void 0===r&&(r={}),!pr(this))return _(_r("read"));if(!ArrayBuffer.isView(e))return _(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return _(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return _(new TypeError("view's buffer must have non-zero byteLength"));if(pe(e.buffer))return _(new TypeError("view's buffer has been detached"));var t;try{t=function(e,r){var t;return Q(e,r),{min:J(null!==(t=null==e?void 0:e.min)&&void 0!==t?t:1,"".concat(r," has member 'min' that"))}}(r,"options")}catch(e){return _(e)}var n,o,a=t.min;if(0===a)return _(new TypeError("options.min must be greater than 0"));if(function(e){return We(e.constructor)}(e)){if(a>e.byteLength)return _(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(a>e.length)return _(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return _(I("read from"));var i=h((function(e,r){n=e,o=r}));return hr(this,e,a,{_chunkSteps:function(e){return n({value:e,done:!1})},_closeSteps:function(e){return n({value:e,done:!0})},_errorSteps:function(e){return o(e)}}),i},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!pr(this))throw _r("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");mr(e,r)}(this)},ReadableStreamBYOBReader}();function pr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof br)}function hr(e,r,t,n){var o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?n._errorSteps(o._storedError):Ue(o._readableStreamController,r,t,n)}function mr(e,r){var t=e._readIntoRequests;e._readIntoRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function _r(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function yr(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(Pe(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function vr(e){var r=e.size;return r||function(){return 1}}function gr(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:G(t),size:void 0===n?void 0:Sr(n,"".concat(r," has member 'size' that"))}}function Sr(e,r){return N(e,r),function(r){return G(e(r))}}function wr(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function Rr(e,r,t){return N(e,t),function(){return C(e,r,[])}}function Tr(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function Pr(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function Cr(e,r){if(!jr(e))throw new TypeError("".concat(r," is not a WritableStream."))}Object.defineProperties(br.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(br.prototype.cancel,"cancel"),f(br.prototype.read,"read"),f(br.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(br.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var qr="function"==typeof AbortController;var Er=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=gr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:wr(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:Rr(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:Tr(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Pr(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if(Wr(this),void 0!==n.type)throw new RangeError("Invalid type is specified");var o=vr(t);!function(e,r,t,n){var o,a,i,u,l=Object.create(Xr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){};a=void 0!==r.write?function(e){return r.write(e,l)}:function(){return m(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return m(void 0)};u=void 0!==r.abort?function(e){return r.abort(e)}:function(){return m(void 0)};Kr(e,l,o,a,i,u,t,n)}(this,n,yr(t,1),o)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!jr(this))throw ot("locked");return Br(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),jr(this)?Br(this)?_(new TypeError("Cannot abort a stream that already has a writer")):kr(this,e):_(ot("abort"))},WritableStream.prototype.close=function(){return jr(this)?Br(this)?_(new TypeError("Cannot close a stream that already has a writer")):Lr(this)?_(new TypeError("Cannot close an already-closing stream")):Ar(this):_(ot("close"))},WritableStream.prototype.getWriter=function(){if(!jr(this))throw ot("getWriter");return Or(this)},WritableStream}();function Or(e){return new xr(e)}function Wr(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new q,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function jr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof Er)}function Br(e){return void 0!==e._writer}function kr(e,r){var t;if("closed"===e._state||"errored"===e._state)return m(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return m(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=h((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||Ir(e,r),a}function Ar(e){var r=e._state;if("closed"===r||"errored"===r)return _(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=h((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&mt(o),Ee(t=e._writableStreamController,Gr,0),et(t),n}function zr(e,r){"writable"!==e._state?Dr(e):Ir(e,r)}function Ir(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&Hr(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&Dr(e)}function Dr(e){e._state="errored",e._writableStreamController[O]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new q,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void Fr(e);v(e._writableStreamController[E](t._reason),(function(){return t._resolve(),Fr(e),null}),(function(r){return t._reject(r),Fr(e),null}))}else Fr(e)}function Lr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Fr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&ct(r,e._storedError)}function Mr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){dt(e)}(t):mt(t)),e._backpressure=r}Object.defineProperties(Er.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),f(Er.prototype.abort,"abort"),f(Er.prototype.close,"close"),f(Er.prototype.getWriter,"getWriter"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Er.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var xr=function(){function WritableStreamDefaultWriter(e){if(V(e,1,"WritableStreamDefaultWriter"),Cr(e,"First parameter"),Br(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!Lr(e)&&e._backpressure?dt(this):pt(this),lt(this);else if("erroring"===t)bt(this,e._storedError),lt(this);else if("closed"===t)pt(this),lt(r=this),ft(r);else{var n=e._storedError;bt(this,n),st(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return Yr(this)?this._closedPromise:_(it("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!Yr(this))throw it("desiredSize");if(void 0===this._ownerWritableStream)throw ut("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return $r(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return Yr(this)?this._readyPromise:_(it("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),Yr(this)?void 0===this._ownerWritableStream?_(ut("abort")):function(e,r){return kr(e._ownerWritableStream,r)}(this,e):_(it("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!Yr(this))return _(it("close"));var e=this._ownerWritableStream;return void 0===e?_(ut("close")):Lr(e)?_(new TypeError("Cannot close an already-closing stream")):Qr(this)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!Yr(this))throw it("releaseLock");void 0!==this._ownerWritableStream&&Vr(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),Yr(this)?void 0===this._ownerWritableStream?_(ut("write to")):Ur(this,e):_(it("write"))},WritableStreamDefaultWriter}();function Yr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof xr)}function Qr(e){return Ar(e._ownerWritableStream)}function Nr(e,r){"pending"===e._closedPromiseState?ct(e,r):function(e,r){st(e,r)}(e,r)}function Hr(e,r){"pending"===e._readyPromiseState?ht(e,r):function(e,r){bt(e,r)}(e,r)}function Vr(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Hr(e,t),Nr(e,t),r._writer=void 0,e._ownerWritableStream=void 0}function Ur(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return rt(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return _(ut("write to"));var a=t._state;if("errored"===a)return _(t._storedError);if(Lr(t)||"closed"===a)return _(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return _(t._storedError);var i=function(e){return h((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{Ee(e,r,t)}catch(r){return void rt(e,r)}var n=e._controlledWritableStream;if(!Lr(n)&&"writable"===n._state){Mr(n,tt(e))}et(e)}(n,r,o),i}Object.defineProperties(xr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),f(xr.prototype.abort,"abort"),f(xr.prototype.close,"close"),f(xr.prototype.releaseLock,"releaseLock"),f(xr.prototype.write,"write"),"symbol"==typeof r.toStringTag&&Object.defineProperty(xr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Gr={},Xr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!Jr(this))throw at("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!Jr(this))throw at("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Jr(this))throw at("error");"writable"===this._controlledWritableStream._state&&nt(this,e)},WritableStreamDefaultController.prototype[E]=function(e){var r=this._abortAlgorithm(e);return Zr(this),r},WritableStreamDefaultController.prototype[O]=function(){Oe(this)},WritableStreamDefaultController}();function Jr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof Xr)}function Kr(e,r,t,n,o,a,i,u){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,Oe(r),r._abortReason=void 0,r._abortController=function(){if(qr)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=u,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var l=tt(r);Mr(e,l),v(m(t()),(function(){return r._started=!0,et(r),null}),(function(t){return r._started=!0,zr(e,t),null}))}function Zr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function $r(e){return e._strategyHWM-e._queueTotalSize}function et(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===Gr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),qe(e);var t=e._closeAlgorithm();Zr(e),v(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&ft(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),zr(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(t);var n=e._writeAlgorithm(r);v(n,(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(qe(e),!Lr(t)&&"writable"===r){var n=tt(e);Mr(t,n)}return et(e),null}),(function(r){return"writable"===t._state&&Zr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,zr(e,r)}(t,r),null}))}(e,t)}}else Dr(r)}function rt(e,r){"writable"===e._controlledWritableStream._state&&nt(e,r)}function tt(e){return $r(e)<=0}function nt(e,r){var t=e._controlledWritableStream;Zr(e),Ir(t,r)}function ot(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function at(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function it(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function ut(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function lt(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function st(e,r){lt(e),ct(e,r)}function ct(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function ft(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function dt(e){e._readyPromise=h((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function bt(e,r){dt(e),ht(e,r)}function pt(e){dt(e),mt(e)}function ht(e,r){void 0!==e._readyPromise_reject&&(R(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function mt(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Xr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Xr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var _t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var yt,vt=(function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(yt=null==_t?void 0:_t.DOMException)?yt:void 0)||function(){var e=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return f(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function gt(e,r,t,n,o,a){var i=Z(e),u=Or(r);e._disturbed=!0;var s=!1,c=m(void 0);return h((function(f,d){var b,p,w,T;if(void 0!==a){if(b=function(){var t=void 0!==a.reason?a.reason:new vt("Aborted","AbortError"),i=[];n||i.push((function(){return"writable"===r._state?kr(r,t):m(void 0)})),o||i.push((function(){return"readable"===e._state?Vt(e,t):m(void 0)})),E((function(){return Promise.all(i.map((function(e){return e()})))}),!0,t)},a.aborted)return void b();a.addEventListener("abort",b)}if(q(e,i._closedPromise,(function(e){return n?O(!0,e):E((function(){return kr(r,e)}),!0,e),null})),q(r,u._closedPromise,(function(r){return o?O(!0,r):E((function(){return Vt(e,r)}),!0,r),null})),p=e,w=i._closedPromise,T=function(){return t?O():E((function(){return function(e){var r=e._ownerWritableStream,t=r._state;return Lr(r)||"closed"===t?m(void 0):"errored"===t?_(r._storedError):Qr(e)}(u)})),null},"closed"===p._state?T():g(w,T),Lr(r)||"closed"===r._state){var P=new TypeError("the destination writable stream closed before all data could be piped to it");o?O(!0,P):E((function(){return Vt(e,P)}),!0,P)}function C(){var e=c;return y(c,(function(){return e!==c?C():void 0}))}function q(e,r,t){"errored"===e._state?t(e._storedError):S(r,t)}function E(e,t,n){function o(){return v(e(),(function(){return W(t,n)}),(function(e){return W(!0,e)})),null}s||(s=!0,"writable"!==r._state||Lr(r)?o():g(C(),o))}function O(e,t){s||(s=!0,"writable"!==r._state||Lr(r)?W(e,t):g(C(),(function(){return W(e,t)})))}function W(e,r){return Vr(u),z(i),void 0!==a&&a.removeEventListener("abort",b),e?d(r):f(void 0),null}R(h((function(e,r){!function t(n){n?e():y(s?m(!0):y(u._readyPromise,(function(){return h((function(e,r){le(i,{_chunkSteps:function(r){c=y(Ur(u,r),void 0,l),e(!1)},_closeSteps:function(){return e(!0)},_errorSteps:r})}))})),t,r)}(!1)})))}))}var St=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!wt(this))throw Bt("desiredSize");return Ot(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!wt(this))throw Bt("close");if(!Wt(this))throw new TypeError("The stream is not in a state that permits close");Ct(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!wt(this))throw Bt("enqueue");if(!Wt(this))throw new TypeError("The stream is not in a state that permits enqueue");return qt(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!wt(this))throw Bt("error");Et(this,e)},ReadableStreamDefaultController.prototype[W]=function(e){Oe(this);var r=this._cancelAlgorithm(e);return Pt(this),r},ReadableStreamDefaultController.prototype[j]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=qe(this);this._closeRequested&&0===this._queue.length?(Pt(this),Ut(r)):Rt(this),e._chunkSteps(t)}else $(r,e),Rt(this)},ReadableStreamDefaultController.prototype[B]=function(){},ReadableStreamDefaultController}();function wt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof St)}function Rt(e){Tt(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Rt(e)),null}),(function(r){return Et(e,r),null}))))}function Tt(e){var r=e._controlledReadableStream;return!!Wt(e)&&(!!e._started&&(!!(Ht(r)&&re(r)>0)||Ot(e)>0))}function Pt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ct(e){if(Wt(e)){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Pt(e),Ut(r))}}function qt(e,r){if(Wt(e)){var t=e._controlledReadableStream;if(Ht(t)&&re(t)>0)ee(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Et(e,r),r}try{Ee(e,r,n)}catch(r){throw Et(e,r),r}}Rt(e)}}function Et(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(Oe(e),Pt(e),Gt(t,r))}function Ot(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Wt(e){var r=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===r}function jt(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,Oe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,Rt(r),null}),(function(e){return Et(r,e),null}))}function Bt(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function kt(e,r){return ke(e._readableStreamController)?function(e){var r,t,n,o,a,i=Z(e),u=!1,l=!1,s=!1,c=!1,f=!1,d=h((function(e){a=e}));function b(e){S(e._closedPromise,(function(r){return e!==i||($e(n._readableStreamController,r),$e(o._readableStreamController,r),c&&f||a(void 0)),null}))}function p(){pr(i)&&(z(i),b(i=Z(e))),le(i,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var t=r,i=r;if(!c&&!f)try{i=Ce(r)}catch(r){return $e(n._readableStreamController,r),$e(o._readableStreamController,r),void a(Vt(e,r))}c||Ze(n._readableStreamController,t),f||Ze(o._readableStreamController,i),u=!1,l?y():s&&v()}))},_closeSteps:function(){u=!1,c||Ke(n._readableStreamController),f||Ke(o._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&nr(n._readableStreamController,0),o._readableStreamController._pendingPullIntos.length>0&&nr(o._readableStreamController,0),c&&f||a(void 0)},_errorSteps:function(){u=!1}})}function _(r,t){ue(i)&&(z(i),b(i=sr(e)));var d=t?o:n,p=t?n:o;hr(i,r,1,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var n=t?f:c;if(t?c:f)n||or(d._readableStreamController,r);else{var o=void 0;try{o=Ce(r)}catch(r){return $e(d._readableStreamController,r),$e(p._readableStreamController,r),void a(Vt(e,r))}n||or(d._readableStreamController,r),Ze(p._readableStreamController,o)}u=!1,l?y():s&&v()}))},_closeSteps:function(e){u=!1;var r=t?f:c,n=t?c:f;r||Ke(d._readableStreamController),n||Ke(p._readableStreamController),void 0!==e&&(r||or(d._readableStreamController,e),!n&&p._readableStreamController._pendingPullIntos.length>0&&nr(p._readableStreamController,0)),r&&n||a(void 0)},_errorSteps:function(){u=!1}})}function y(){if(u)return l=!0,m(void 0);u=!0;var e=rr(n._readableStreamController);return null===e?p():_(e._view,!1),m(void 0)}function v(){if(u)return s=!0,m(void 0);u=!0;var e=rr(o._readableStreamController);return null===e?p():_(e._view,!0),m(void 0)}function g(n){if(c=!0,r=n,f){var o=fe([r,t]),i=Vt(e,o);a(i)}return d}function w(n){if(f=!0,t=n,c){var o=fe([r,t]),i=Vt(e,o);a(i)}return d}function R(){}return n=Yt(R,y,g),o=Yt(R,v,w),b(i),[n,o]}(e):function(e,r){var t,n,o,a,i,u=Z(e),l=!1,s=!1,c=!1,f=!1,d=h((function(e){i=e}));function b(){return l?(s=!0,m(void 0)):(l=!0,le(u,{_chunkSteps:function(e){T((function(){s=!1;var r=e,t=e;c||qt(o._readableStreamController,r),f||qt(a._readableStreamController,t),l=!1,s&&b()}))},_closeSteps:function(){l=!1,c||Ct(o._readableStreamController),f||Ct(a._readableStreamController),c&&f||i(void 0)},_errorSteps:function(){l=!1}}),m(void 0))}function p(r){if(c=!0,t=r,f){var o=fe([t,n]),a=Vt(e,o);i(a)}return d}function _(r){if(f=!0,n=r,c){var o=fe([t,n]),a=Vt(e,o);i(a)}return d}function y(){}return o=xt(y,b,p),a=xt(y,b,_),S(u._closedPromise,(function(e){return Et(o._readableStreamController,e),Et(a._readableStreamController,e),c&&f||i(void 0),null})),[o,a]}(e)}function At(e){return s(r=e)&&void 0!==r.getReader?function(e){var r;function t(){var t;try{t=e.read()}catch(e){return _(e)}return w(t,(function(e){if(!s(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)Ct(r._readableStreamController);else{var t=e.value;qt(r._readableStreamController,t)}}))}function n(r){try{return m(e.cancel(r))}catch(e){return _(e)}}return r=xt(l,t,n,0),r}(e.getReader()):function(e){var r,t=ve(e,"async");function n(){var e;try{e=function(e){var r=P(e.nextMethod,e.iterator,[]);if(!s(r))throw new TypeError("The iterator.next() method must return an object");return r}(t)}catch(e){return _(e)}return w(m(e),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");var t=function(e){return Boolean(e.done)}(e);if(t)Ct(r._readableStreamController);else{var n=function(e){return e.value}(e);qt(r._readableStreamController,n)}}))}function o(e){var r,n,o=t.iterator;try{r=me(o,"return")}catch(e){return _(e)}if(void 0===r)return m(void 0);try{n=P(r,o,[e])}catch(e){return _(e)}return w(m(n),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return r=xt(l,n,o,0),r}(e);var r}function zt(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function It(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function Dt(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function Lt(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function Ft(e,r){Q(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}Object.defineProperties(St.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),f(St.prototype.close,"close"),f(St.prototype.enqueue,"enqueue"),f(St.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(St.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var Mt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=gr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,u=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:J(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:zt(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:It(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:Dt(i,t,"".concat(r," has member 'start' that")),type:void 0===u?void 0:Lt(u,"".concat(r," has member 'type' that"))}}(e,"First parameter");if(Qt(this),"bytes"===n.type){if(void 0!==t.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,r,t){var n,o,a,i=Object.create(Be.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return m(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};var u=r.autoAllocateChunkSize;if(0===u)throw new TypeError("autoAllocateChunkSize must be greater than 0");ar(e,i,n,o,a,t,u)}(this,n,yr(t,0))}else{var o=vr(t);!function(e,r,t,n){var o,a,i,u=Object.create(St.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){},a=void 0!==r.pull?function(){return r.pull(u)}:function(){return m(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)},jt(e,u,o,a,i,t,n)}(this,n,yr(t,1),o)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!Nt(this))throw Xt("locked");return Ht(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),Nt(this)?Ht(this)?_(new TypeError("Cannot cancel a stream that already has a reader")):Vt(this,e):_(Xt("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!Nt(this))throw Xt("getReader");return void 0===function(e,r){Q(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:lr(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?Z(this):sr(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!Nt(this))throw Xt("pipeThrough");V(e,1,"pipeThrough");var t=function(e,r){Q(e,r);var t=null==e?void 0:e.readable;U(t,"readable","ReadableWritablePair"),K(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return U(n,"writable","ReadableWritablePair"),Cr(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}(e,"First parameter"),n=Ft(r,"Second parameter");if(Ht(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Br(t.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return R(gt(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!Nt(this))return _(Xt("pipeTo"));if(void 0===e)return _("Parameter 1 is required in 'pipeTo'.");if(!jr(e))return _(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=Ft(r,"Second parameter")}catch(e){return _(e)}return Ht(this)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Br(e)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gt(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!Nt(this))throw Xt("tee");return fe(kt(this))},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!Nt(this))throw Xt("values");var r,t,n,o,a,i=function(e,r){Q(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=Z(r),o=new Se(n,t),(a=Object.create(we))._asyncIteratorImpl=o,a},ReadableStream.prototype[ye]=function(e){return this.values(e)},ReadableStream.from=function(e){return At(e)},ReadableStream}();function xt(e,r,t,n,o){void 0===n&&(n=1),void 0===o&&(o=function(){return 1});var a=Object.create(Mt.prototype);return Qt(a),jt(a,Object.create(St.prototype),e,r,t,n,o),a}function Yt(e,r,t){var n=Object.create(Mt.prototype);return Qt(n),ar(n,Object.create(Be.prototype),e,r,t,0,void 0),n}function Qt(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Nt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof Mt)}function Ht(e){return void 0!==e._reader}function Vt(e,r){if(e._disturbed=!0,"closed"===e._state)return m(void 0);if("errored"===e._state)return _(e._storedError);Ut(e);var t=e._reader;if(void 0!==t&&pr(t)){var n=t._readIntoRequests;t._readIntoRequests=new q,n.forEach((function(e){e._closeSteps(void 0)}))}return w(e._readableStreamController[W](r),l)}function Ut(e){e._state="closed";var r=e._reader;if(void 0!==r&&(M(r),ue(r))){var t=r._readRequests;r._readRequests=new q,t.forEach((function(e){e._closeSteps()}))}}function Gt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(F(t,r),ue(t)?se(t,r):mr(t,r))}function Xt(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function Jt(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark;return U(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:G(t)}}Object.defineProperties(Mt,{from:{enumerable:!0}}),Object.defineProperties(Mt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),f(Mt.from,"from"),f(Mt.prototype.cancel,"cancel"),f(Mt.prototype.getReader,"getReader"),f(Mt.prototype.pipeThrough,"pipeThrough"),f(Mt.prototype.pipeTo,"pipeTo"),f(Mt.prototype.tee,"tee"),f(Mt.prototype.values,"values"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Mt.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Mt.prototype,ye,{value:Mt.prototype.values,writable:!0,configurable:!0});var Kt=function(e){return e.byteLength};f(Kt,"size");var Zt=function(){function ByteLengthQueuingStrategy(e){V(e,1,"ByteLengthQueuingStrategy"),e=Jt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!en(this))throw $t("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!en(this))throw $t("size");return Kt},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function $t(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function en(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof Zt)}Object.defineProperties(Zt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Zt.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var rn=function(){return 1};f(rn,"size");var tn=function(){function CountQueuingStrategy(e){V(e,1,"CountQueuingStrategy"),e=Jt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!on(this))throw nn("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!on(this))throw nn("size");return rn},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function nn(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function on(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof tn)}function an(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function un(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function ln(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function sn(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}Object.defineProperties(tn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(tn.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var cn=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=gr(r,"Second parameter"),o=gr(t,"Third parameter"),a=function(e,r){Q(e,r);var t=null==e?void 0:e.cancel,n=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,u=null==e?void 0:e.writableType;return{cancel:void 0===t?void 0:sn(t,e,"".concat(r," has member 'cancel' that")),flush:void 0===n?void 0:an(n,e,"".concat(r," has member 'flush' that")),readableType:o,start:void 0===a?void 0:un(a,e,"".concat(r," has member 'start' that")),transform:void 0===i?void 0:ln(i,e,"".concat(r," has member 'transform' that")),writableType:u}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,u=yr(o,0),l=vr(o),s=yr(n,1),c=vr(n);!function(e,r,t,n,o,a){function i(){return r}function u(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return w(e._backpressureChangePromise,(function(){var n=e._writable;if("erroring"===n._state)throw n._storedError;return gn(t,r)}))}return gn(t,r)}(e,r)}function l(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._readable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return yn(t),v(o,(function(){return"errored"===n._state?Rn(t,n._storedError):(Et(n._readableStreamController,r),wn(t)),null}),(function(e){return Et(n._readableStreamController,e),Rn(t,e),null})),t._finishPromise}(e,r)}function s(){return function(e){var r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;var t=e._readable;r._finishPromise=h((function(e,t){r._finishPromise_resolve=e,r._finishPromise_reject=t}));var n=r._flushAlgorithm();return yn(r),v(n,(function(){return"errored"===t._state?Rn(r,t._storedError):(Ct(t._readableStreamController),wn(r)),null}),(function(e){return Et(t._readableStreamController,e),Rn(r,e),null})),r._finishPromise}(e)}function c(){return function(e){return hn(e,!1),e._backpressureChangePromise}(e)}function f(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._writable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return yn(t),v(o,(function(){return"errored"===n._state?Rn(t,n._storedError):(rt(n._writableStreamController,r),pn(e),wn(t)),null}),(function(r){return rt(n._writableStreamController,r),pn(e),Rn(t,r),null})),t._finishPromise}(e,r)}e._writable=function(e,r,t,n,o,a){void 0===o&&(o=1),void 0===a&&(a=function(){return 1});var i=Object.create(Er.prototype);return Wr(i),Kr(i,Object.create(Xr.prototype),e,r,t,n,o,a),i}(i,u,s,l,t,n),e._readable=xt(i,c,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,hn(e,!0),e._transformStreamController=void 0}(this,h((function(e){i=e})),s,c,u,l),function(e,r){var t,n,o,a=Object.create(mn.prototype);t=void 0!==r.transform?function(e){return r.transform(e,a)}:function(e){try{return vn(a,e),m(void 0)}catch(e){return _(e)}};n=void 0!==r.flush?function(){return r.flush(a)}:function(){return m(void 0)};o=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};!function(e,r,t,n,o){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n,r._cancelAlgorithm=o,r._finishPromise=void 0,r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0}(e,a,t,n,o)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!fn(this))throw Tn("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!fn(this))throw Tn("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function fn(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof cn)}function dn(e,r){Et(e._readable._readableStreamController,r),bn(e,r)}function bn(e,r){yn(e._transformStreamController),rt(e._writable._writableStreamController,r),pn(e)}function pn(e){e._backpressure&&hn(e,!1)}function hn(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=h((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(cn.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(cn.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var mn=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!_n(this))throw Sn("desiredSize");return Ot(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!_n(this))throw Sn("enqueue");vn(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!_n(this))throw Sn("error");var r;r=e,dn(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!_n(this))throw Sn("terminate");!function(e){var r=e._controlledTransformStream;Ct(r._readable._readableStreamController);var t=new TypeError("TransformStream terminated");bn(r,t)}(this)},TransformStreamDefaultController}();function _n(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof mn)}function yn(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function vn(e,r){var t=e._controlledTransformStream,n=t._readable._readableStreamController;if(!Wt(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{qt(n,r)}catch(e){throw bn(t,e),t._readable._storedError}var o=function(e){return!Tt(e)}(n);o!==t._backpressure&&hn(t,!0)}function gn(e,r){return w(e._transformAlgorithm(r),void 0,(function(r){throw dn(e._controlledTransformStream,r),r}))}function Sn(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function wn(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Rn(e,r){void 0!==e._finishPromise_reject&&(R(e._finishPromise),e._finishPromise_reject(r),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Tn(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}Object.defineProperties(mn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),f(mn.prototype.enqueue,"enqueue"),f(mn.prototype.error,"error"),f(mn.prototype.terminate,"terminate"),"symbol"==typeof r.toStringTag&&Object.defineProperty(mn.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Pn={ReadableStream:Mt,ReadableStreamDefaultController:St,ReadableByteStreamController:Be,ReadableStreamBYOBRequest:je,ReadableStreamDefaultReader:ie,ReadableStreamBYOBReader:br,WritableStream:Er,WritableStreamDefaultController:Xr,WritableStreamDefaultWriter:xr,ByteLengthQueuingStrategy:Zt,CountQueuingStrategy:tn,TransformStream:cn,TransformStreamDefaultController:mn};if(void 0!==_t)for(var Cn in Pn)Object.prototype.hasOwnProperty.call(Pn,Cn)&&Object.defineProperty(_t,Cn,{value:Pn[Cn],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=Zt,e.CountQueuingStrategy=tn,e.ReadableByteStreamController=Be,e.ReadableStream=Mt,e.ReadableStreamBYOBReader=br,e.ReadableStreamBYOBRequest=je,e.ReadableStreamDefaultController=St,e.ReadableStreamDefaultReader=ie,e.TransformStream=cn,e.TransformStreamDefaultController=mn,e.WritableStream=Er,e.WritableStreamDefaultController=Xr,e.WritableStreamDefaultWriter=xr})); +//# sourceMappingURL=polyfill.min.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js.map new file mode 100644 index 0000000..8cd66dc --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.min.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","concat","__generator","thisArg","body","f","y","t","g","_","label","sent","trys","ops","next","verb","throw","return","this","n","v","op","TypeError","call","done","value","pop","length","push","e","step","__values","o","s","m","i","__await","__asyncGenerator","_arguments","generator","asyncIterator","apply","q","Promise","a","b","resume","r","resolve","then","fulfill","reject","settle","shift","__asyncDelegator","p","__asyncValues","d","noop","typeIsObject","x","SuppressedError","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","configurable","_a","originalPromise","originalPromiseThen","prototype","originalPromiseReject","bind","newPromise","executor","promiseResolvedWith","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise_1","cb","reflectCall","F","V","args","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","get","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","forEach","node","peek","front","cursor","AbortSteps","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","defineProperties","enumerable","closed","toStringTag","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","SymbolAsyncIterator","_c","_b","for","GetIterator","hint","method","syncIteratorRecord","syncIterable","nextMethod","CreateAsyncFromSyncIterator","AsyncIteratorPrototype","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","_this","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","view","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","desiredSize","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","constructor","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","byobRequest","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","writeAlgorithm","closeAlgorithm","abortAlgorithm","WritableStreamDefaultController","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","abortRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","locked","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","abortReason","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","action","actions","shutdownWithAction","all","map","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed_1","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","startPromise_resolve","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","transformAlgorithm","flushAlgorithm","TransformStreamDefaultController","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;0PAEA,IAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACA,SAAAE,GAAe,MAAA,UAAAC,OAAUD,EAA+B,IAAA,ECuHrD,SAASE,EAAYC,EAASC,GACjC,IAAsGC,EAAGC,EAAGC,EAAGC,EAA3GC,EAAI,CAAEC,MAAO,EAAGC,KAAM,WAAa,GAAW,EAAPJ,EAAE,GAAQ,MAAMA,EAAE,GAAI,OAAOA,EAAE,EAAK,EAAEK,KAAM,GAAIC,IAAK,IAChG,OAAOL,EAAI,CAAEM,KAAMC,EAAK,GAAIC,MAASD,EAAK,GAAIE,OAAUF,EAAK,IAAwB,mBAAXjB,SAA0BU,EAAEV,OAAOC,UAAY,WAAa,OA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AC3BoN,yBAAwBA,GAExB2B,eAAcA,GACdc,gCAA+BA,GAC/BU,4BAA2BA,GAE3BmO,0BAAyBA,GACzBK,qBAAoBA,GAEpBQ,gBAAeA,GACf0C,iCAAgCA,IAIlC,QAAuB,IAAZ9L,GACT,IAAK,IAAM/S,MAAQ4f,GACbhqB,OAAOM,UAAUgI,eAAejL,KAAK2sB,GAAS5f,KAChDpK,OAAOC,eAAekd,GAAS/S,GAAM,CACnC7M,MAAOysB,GAAQ5f,IACfwT,UAAU,EACV1d,cAAc","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs new file mode 100644 index 0000000..f1dab86 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs @@ -0,0 +1,4991 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +var _a$1, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +var _a; +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +var exports = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (var prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs.map new file mode 100644 index 0000000..a8b2b08 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/polyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;IACN,UAAA,WAAW,IAA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,IAAM,OAAO,GAAG;AACd,IAAA,cAAc,EAAA,cAAA;AACd,IAAA,+BAA+B,EAAA,+BAAA;AAC/B,IAAA,4BAA4B,EAAA,4BAAA;AAC5B,IAAA,yBAAyB,EAAA,yBAAA;AACzB,IAAA,2BAA2B,EAAA,2BAAA;AAC3B,IAAA,wBAAwB,EAAA,wBAAA;AAExB,IAAA,cAAc,EAAA,cAAA;AACd,IAAA,+BAA+B,EAAA,+BAAA;AAC/B,IAAA,2BAA2B,EAAA,2BAAA;AAE3B,IAAA,yBAAyB,EAAA,yBAAA;AACzB,IAAA,oBAAoB,EAAA,oBAAA;AAEpB,IAAA,eAAe,EAAA,eAAA;AACf,IAAA,gCAAgC,EAAA,gCAAA;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,IAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js new file mode 100644 index 0000000..75ddde2 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js @@ -0,0 +1,4737 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es2018.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map new file mode 100644 index 0000000..6d107ac --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,I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AAC,MAAM,CAAC,CAAC;IACpC,QAAA,oCAAoC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IACpD,QAAA,OAAO,IAAI,CAAC;IACd,KAAC,CAAC,CAAC;QAEH,OAAO,UAAU,CAAC,cAAc,CAAC;IACnC,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY,EAAA;IACxD,IAAA,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,CAAA,uDAAA,CAAyD,CAAC,CAAC;IACjH,CAAC;IAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;IACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;YACnD,OAAO;SACR;QAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;IACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;IACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;YAClD,OAAO;SACR;IAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;IACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs new file mode 100644 index 0000000..431260f --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs @@ -0,0 +1,4717 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es2018.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map new file mode 100644 index 0000000..0a16b7c --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;AAChC,YAAA,KAAK,EAAE,IAAI;AACX,YAAA,YAAY,EAAE,IAAI;AACnB,SAAA,CAAC,CAAC;KACJ;AAAC,IAAA,OAAA,EAAA,EAAM;;;KAG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,sBAAsB,EAAE,CAAC;AACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;AACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js new file mode 100644 index 0000000..4e4206d --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js @@ -0,0 +1,4810 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es6.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map new file mode 100644 index 0000000..1f0b187 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,OAAA,EAAA,EAAM;;;SAGP;IACH;;IC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,M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;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs new file mode 100644 index 0000000..1d4d689 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs @@ -0,0 +1,4790 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } +}; +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es6.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map new file mode 100644 index 0000000..929200b --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM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C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js new file mode 100644 index 0000000..69fd00d --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js @@ -0,0 +1,4983 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + var _a$1, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + var _a; + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.js.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js.map new file mode 100644 index 0000000..d151897 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","_a","queueMicr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oC,CAAC,UAAiD,EAAE,MAAW,EAAA;IACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;YAClD,OAAO;SACR;IAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;IACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs new file mode 100644 index 0000000..9f07fe8 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs @@ -0,0 +1,4963 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +var _a$1, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +var _a; +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.mjs.map diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map new file mode 100644 index 0000000..d7df2bd --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Sym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AA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts b/src/libMPC/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts new file mode 100644 index 0000000..2d09835 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts @@ -0,0 +1,24 @@ +/// +/// +import { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; +export * from './ponyfill'; +declare global { + interface ReadableStream extends AsyncIterable { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts new file mode 100644 index 0000000..d31068b --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts @@ -0,0 +1,780 @@ +/// +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + readonly size: (chunk: ArrayBufferView) => number; +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + readonly size: (chunk: any) => 1; +} +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /* + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + readonly byobRequest: ReadableStreamBYOBRequest | null; + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream implements AsyncIterable { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /* + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + readonly locked: boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterableIterator { + next(): Promise>; + return(value?: any): Promise>; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /* + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + readonly view: ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /* + * The readable side of the transform stream. + */ + readonly readable: ReadableStream; + /* + * The writable side of the transform stream. + */ + readonly writable: WritableStream; +} +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + readonly desiredSize: number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /* + * Returns whether or not the writable stream is locked to a writer. + */ + readonly locked: boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /* + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + readonly abortReason: any; + /* + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + readonly signal: AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /* + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + readonly desiredSize: number | null; + /* + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + readonly ready: Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} +export {}; diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts new file mode 100644 index 0000000..1e24288 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts @@ -0,0 +1,28 @@ +/// +/// + +import type { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; + +export * from './ponyfill'; + +declare global { + interface ReadableStream extends AsyncIterable { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts new file mode 100644 index 0000000..b1fd4ae --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts @@ -0,0 +1,821 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size(): (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size(): (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream implements AsyncIterable { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked(): boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterableIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view(): ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + get readable(): ReadableStream; + /** + * The writable side of the transform stream. + */ + get writable(): WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize(): number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked(): boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason(): any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal(): AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize(): number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready(): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/src/libMPC/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json b/src/libMPC/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json new file mode 100644 index 0000000..b18fd2a --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.39.1" + } + ] +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/es2018/package.json b/src/libMPC/node_modules/web-streams-polyfill/es2018/package.json new file mode 100644 index 0000000..97f8fb1 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/es2018/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es2018", + "main": "../dist/polyfill.es2018", + "browser": "../dist/polyfill.es2018.min.js", + "module": "../dist/polyfill.es2018.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/es6/package.json b/src/libMPC/node_modules/web-streams-polyfill/es6/package.json new file mode 100644 index 0000000..ca3909b --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/es6/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es6", + "main": "../dist/polyfill.es6", + "browser": "../dist/polyfill.es6.min.js", + "module": "../dist/polyfill.es6.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/package.json b/src/libMPC/node_modules/web-streams-polyfill/package.json new file mode 100644 index 0000000..fa7d164 --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/package.json @@ -0,0 +1,83 @@ +{ + "name": "web-streams-polyfill", + "version": "3.3.3", + "description": "Web Streams, based on the WHATWG spec reference implementation", + "main": "dist/polyfill", + "browser": "dist/polyfill.min.js", + "module": "dist/polyfill.mjs", + "types": "dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "dist/types/*": [ + "dist/types/ts3.6/*" + ] + } + }, + "scripts": { + "test": "npm run test:types && npm run test:unit && npm run test:wpt", + "test:wpt": "npm run test:wpt:node && npm run test:wpt:chromium && npm run test:wpt:firefox", + "test:wpt:node": "node --expose_gc ./test/wpt/node/run.js", + "test:wpt:chromium": "node ./test/wpt/browser/run.js --browser chromium", + "test:wpt:firefox": "node ./test/wpt/browser/run.js --browser firefox", + "test:types": "tsc -p ./test/types/tsconfig.json", + "test:unit": "jasmine --config=test/unit/jasmine.json", + "lint": "eslint \"src/**/*.ts\"", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "rollup -c", + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run", + "accept:types": "npm run build:types -- --local", + "postbuild:types": "downlevel-dts ./dist/types/ts3.6/ ./dist/types/ --to=3.5 && node ./build/downlevel-dts.js", + "prepare": "npm run build" + }, + "files": [ + "dist", + "es6", + "es2018", + "ponyfill" + ], + "engines": { + "node": ">= 8" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git" + }, + "keywords": [ + "streams", + "whatwg", + "polyfill" + ], + "author": "Mattias Buelens ", + "contributors": [ + "Diwank Singh " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues" + }, + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme", + "devDependencies": { + "@microsoft/api-extractor": "^7.39.1", + "@rollup/plugin-inject": "^5.0.5", + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.5", + "@types/node": "^18.19.4", + "@typescript-eslint/eslint-plugin": "^6.17.0", + "@typescript-eslint/parser": "^6.17.0", + "@ungap/promise-all-settled": "^1.1.2", + "downlevel-dts": "^0.11.0", + "eslint": "^8.56.0", + "jasmine": "^5.1.0", + "micromatch": "^4.0.5", + "minimist": "^1.2.5", + "playwright": "^1.14.1", + "recursive-readdir": "^2.2.2", + "rollup": "^4.9.2", + "ts-morph": "^10.0.2", + "tslib": "^2.6.2", + "typescript": "^5.3.3", + "wpt-runner": "^5.0.0" + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es2018/package.json b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es2018/package.json new file mode 100644 index 0000000..26816ac --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es2018/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es2018", + "main": "../../dist/ponyfill.es2018", + "module": "../../dist/ponyfill.es2018.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es6/package.json b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es6/package.json new file mode 100644 index 0000000..b54520d --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/es6/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es6", + "main": "../../dist/ponyfill.es6", + "module": "../../dist/ponyfill.es6.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/src/libMPC/node_modules/web-streams-polyfill/ponyfill/package.json b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/package.json new file mode 100644 index 0000000..36e9fbe --- /dev/null +++ b/src/libMPC/node_modules/web-streams-polyfill/ponyfill/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill", + "main": "../dist/ponyfill", + "module": "../dist/ponyfill.mjs", + "types": "../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/src/libMPC/node_modules/wif/.npmignore b/src/libMPC/node_modules/wif/.npmignore new file mode 100644 index 0000000..c9106a7 --- /dev/null +++ b/src/libMPC/node_modules/wif/.npmignore @@ -0,0 +1,2 @@ +node_modules +.nyc_output diff --git a/src/libMPC/node_modules/wif/.travis.yml b/src/libMPC/node_modules/wif/.travis.yml new file mode 100644 index 0000000..85a39cb --- /dev/null +++ b/src/libMPC/node_modules/wif/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "4" + - "5" + - "7" +matrix: + include: + - node_js: "7" + env: TEST_SUITE=standard + - node_js: "7" + env: TEST_SUITE=coverage +env: + - TEST_SUITE=unit +script: npm run-script $TEST_SUITE diff --git a/src/libMPC/node_modules/wif/LICENSE b/src/libMPC/node_modules/wif/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/src/libMPC/node_modules/wif/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +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. diff --git a/src/libMPC/node_modules/wif/README.md b/src/libMPC/node_modules/wif/README.md new file mode 100644 index 0000000..edefc3c --- /dev/null +++ b/src/libMPC/node_modules/wif/README.md @@ -0,0 +1,32 @@ +# WIF + +[![TRAVIS](https://secure.travis-ci.org/bitcoinjs/wif.png)](http://travis-ci.org/bitcoinjs/wif) +[![NPM](http://img.shields.io/npm/v/wif.svg)](https://www.npmjs.org/package/wif) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Bitcoin Wallet Import Format encoding/decoding module. + + +## Example + +``` javascript +var wif = require('wif') + +var privateKey = new Buffer('0000000000000000000000000000000000000000000000000000000000000001', 'hex') + +var key = wif.encode(128, privateKey, true) +// => KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn + +var obj = wif.decode(key) +// => { +// version: 128, +// privateKey: , +// compressed: true +//} + +wif.encode(obj) +// => KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn +``` + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/wif/index.js b/src/libMPC/node_modules/wif/index.js new file mode 100644 index 0000000..7ac66f7 --- /dev/null +++ b/src/libMPC/node_modules/wif/index.js @@ -0,0 +1,63 @@ +var bs58check = require('bs58check') + +function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } +} + +function encodeRaw (version, privateKey, compressed) { + var result = new Buffer(compressed ? 34 : 33) + + result.writeUInt8(version, 0) + privateKey.copy(result, 1) + + if (compressed) { + result[33] = 0x01 + } + + return result +} + +function decode (string, version) { + return decodeRaw(bs58check.decode(string), version) +} + +function encode (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) +} + +module.exports = { + decode: decode, + decodeRaw: decodeRaw, + encode: encode, + encodeRaw: encodeRaw +} diff --git a/src/libMPC/node_modules/wif/node_modules/base-x/LICENSE.md b/src/libMPC/node_modules/wif/node_modules/base-x/LICENSE.md new file mode 100644 index 0000000..c5dca45 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/base-x/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2018 base-x contributors +Copyright (c) 2014-2018 The Bitcoin Core developers + +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. diff --git a/src/libMPC/node_modules/wif/node_modules/base-x/README.md b/src/libMPC/node_modules/wif/node_modules/base-x/README.md new file mode 100644 index 0000000..042647c --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/base-x/README.md @@ -0,0 +1,67 @@ +# base-x + +[![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) +[![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Fast base encoding / decoding of any given alphabet using bitcoin style leading +zero compression. + +**WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. + +## Example + +Base58 + +``` javascript +var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +var bs58 = require('base-x')(BASE58) + +var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') + +console.log(decoded) +// => + +console.log(bs58.encode(decoded)) +// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr +``` + +### Alphabets + +See below for a list of commonly recognized alphabets, and their respective base. + +Base | Alphabet +------------- | ------------- +2 | `01` +8 | `01234567` +11 | `0123456789a` +16 | `0123456789abcdef` +32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` +32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) +36 | `0123456789abcdefghijklmnopqrstuvwxyz` +58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` +62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` +64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` +67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` + + +## How it works + +It encodes octet arrays by doing long divisions on all significant digits in the +array, creating a representation of that number in the new base. Then for every +leading zero in the input (not significant as a number) it will encode as a +single leader character. This is the first in the alphabet and will decode as 8 +bits. The other characters depend upon the base. For example, a base58 alphabet +packs roughly 5.858 bits per character. + +This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode +to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each +character. + +While unusual, this does mean that no padding is required and it works for bases +like 43. + + +## LICENSE [MIT](LICENSE) +A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. diff --git a/src/libMPC/node_modules/wif/node_modules/base-x/package.json b/src/libMPC/node_modules/wif/node_modules/base-x/package.json new file mode 100644 index 0000000..8f3fb88 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/base-x/package.json @@ -0,0 +1,49 @@ +{ + "name": "base-x", + "version": "3.0.10", + "description": "Fast base encoding / decoding of any given alphabet", + "keywords": [ + "base-x", + "base58", + "base62", + "base64", + "crypto", + "crytography", + "decode", + "decoding", + "encode", + "encoding" + ], + "homepage": "https://github.com/cryptocoinjs/base-x", + "bugs": { + "url": "https://github.com/cryptocoinjs/base-x/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "files": [ + "src" + ], + "main": "src/index.js", + "types": "src/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/cryptocoinjs/base-x.git" + }, + "scripts": { + "build": "tsc -p ./tsconfig.json ; standard --fix", + "gitdiff": "npm run build && git diff --exit-code", + "prepublish": "npm run gitdiff", + "standard": "standard", + "test": "npm run unit && npm run standard", + "unit": "tape test/*.js" + }, + "devDependencies": { + "@types/node": "12.0.10", + "standard": "^10.0.3", + "tape": "^4.5.1", + "typescript": "3.5.2" + }, + "dependencies": { + "safe-buffer": "^5.0.1" + } +} diff --git a/src/libMPC/node_modules/wif/node_modules/base-x/src/index.d.ts b/src/libMPC/node_modules/wif/node_modules/base-x/src/index.d.ts new file mode 100644 index 0000000..0612af9 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/base-x/src/index.d.ts @@ -0,0 +1,10 @@ +/// +declare function base(ALPHABET: string): base.BaseConverter; +export = base; +declare namespace base { + interface BaseConverter { + encode(buffer: Buffer | number[] | Uint8Array): string; + decodeUnsafe(string: string): Buffer | undefined; + decode(string: string): Buffer; + } +} diff --git a/src/libMPC/node_modules/wif/node_modules/base-x/src/index.js b/src/libMPC/node_modules/wif/node_modules/base-x/src/index.js new file mode 100644 index 0000000..8500ac0 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/base-x/src/index.js @@ -0,0 +1,119 @@ +'use strict' +// 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. +// @ts-ignore +var _Buffer = require('safe-buffer').Buffer +function base (ALPHABET) { + 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 + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) } + if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') } + 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 + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer.alloc(0) } + var psz = 0 + // 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 (psz < source.length) { + // 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 leading zeroes in b256. + var it4 = size - length + while (it4 !== size && b256[it4] === 0) { + it4++ + } + var vch = _Buffer.allocUnsafe(zeroes + (size - it4)) + vch.fill(0x00, 0, zeroes) + var j = zeroes + while (it4 !== size) { + vch[j++] = b256[it4++] + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string) + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } +} +module.exports = base diff --git a/src/libMPC/node_modules/wif/node_modules/bs58/CHANGELOG.md b/src/libMPC/node_modules/wif/node_modules/bs58/CHANGELOG.md new file mode 100644 index 0000000..f6f1ffb --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58/CHANGELOG.md @@ -0,0 +1,61 @@ +4.0.0 / 2016-12-3 +------------------ +- `decode` now returns a `Buffer` again, to avoid potential cryptographic errors. [Daniel Cousens / #21](https://github.com/cryptocoinjs/bs58/pull/21) + +3.0.0 / 2015-08-18 +------------------ +- refactored module into generic [`base-x`](https://github.com/cryptocoinjs/base-x). + +2.0.1 / 2014-12-23 +------------------ +- performance boost in `encode()` [#10](https://github.com/cryptocoinjs/bs58/pull/10) + +2.0.0 / 2014-10-03 +------------------ +- `decode` now returns an `Array` instead of `Buffer` to keep things simple. [Daniel Cousens / #9](https://github.com/cryptocoinjs/bs58/pull/9) + +1.2.1 / 2014-07-24 +------------------ +* speed optimizations [Daniel Cousens / #8](https://github.com/cryptocoinjs/bs58/pull/8) + +1.2.0 / 2014-06-29 +------------------ +* removed `bigi` dep, implemented direct byte conversion [Jared Deckard / #6](https://github.com/cryptocoinjs/bs58/pull/6) + +1.1.0 / 2014-06-26 +------------------ +* user `Buffer` internally for calculations, providing cleaner code and a performance increase. [Daniel Cousens](https://github.com/cryptocoinjs/bs58/commit/129c71de8bc1e36f113bce06da0616066f41c5ca) + +1.0.0 / 2014-05-27 +------------------ +* removed `binstring` dep, `Buffer` now only input to `encode()` and output of `decode()` +* update `bigi` from `~0.3.0` to `^1.1.0` +* added travis-ci support +* added coveralls support +* modified tests and library to handle fixture style testing (thanks to bitcoinjs-lib devs and [Daniel Cousens](https://github.com/dcousens)) + + +0.3.0 / 2014-02-24 +------------------ +* duck type input to `encode` and change output of `decode` to `Buffer`. + + +0.2.1 / 2014-02-24 +------------------ +* removed bower and component support. Closes #1 +* convert from 4 spaces to 2 + + +0.2.0 / 2013-12-07 +------------------ +* renamed from `cryptocoin-base58` to `bs58` + + +0.1.0 / 2013-11-20 +------------------ +* removed AMD support + + +0.0.1 / 2013-11-04 +------------------ +* initial release diff --git a/src/libMPC/node_modules/wif/node_modules/bs58/README.md b/src/libMPC/node_modules/wif/node_modules/bs58/README.md new file mode 100644 index 0000000..2d5e624 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58/README.md @@ -0,0 +1,71 @@ +bs58 +==== + +[![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) + +JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. + +**Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. + + +Install +------- + + npm i --save bs58 + + +API +--- + +### encode(input) + +`input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. + +**example**: + +```js +const bs58 = require('bs58') + +const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') +const address = bs58.encode(bytes) +console.log(address) +// => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS +``` + + +### decode(input) + +`input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). + +**example**: + +```js +const bs58 = require('bs58') + +const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' +const bytes = bs58.decode(address) +console.log(out.toString('hex')) +// => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 +``` + +Hack / Test +----------- + +Uses JavaScript standard style. Read more: + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + + +Credits +------- +- [Mike Hearn](https://github.com/mikehearn) for original Java implementation +- [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript +- [Stephan Pair](https://github.com/gasteve) for buffer improvements +- [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib +- [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency + + +License +------- + +MIT diff --git a/src/libMPC/node_modules/wif/node_modules/bs58/index.js b/src/libMPC/node_modules/wif/node_modules/bs58/index.js new file mode 100644 index 0000000..c6ae375 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58/index.js @@ -0,0 +1,4 @@ +var basex = require('base-x') +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +module.exports = basex(ALPHABET) diff --git a/src/libMPC/node_modules/wif/node_modules/bs58/package.json b/src/libMPC/node_modules/wif/node_modules/bs58/package.json new file mode 100644 index 0000000..da0ca3c --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58/package.json @@ -0,0 +1,37 @@ +{ + "name": "bs58", + "version": "4.0.1", + "description": "Base 58 encoding / decoding", + "keywords": [ + "base58", + "bitcoin", + "crypto", + "crytography", + "decode", + "decoding", + "encode", + "encoding", + "litecoin" + ], + "license": "MIT", + "devDependencies": { + "standard": "*", + "tape": "^4.6.3" + }, + "repository": { + "url": "https://github.com/cryptocoinjs/bs58", + "type": "git" + }, + "files": [ + "./index.js" + ], + "main": "./index.js", + "scripts": { + "standard": "standard", + "test": "npm run standard && npm run unit", + "unit": "tape test/index.js" + }, + "dependencies": { + "base-x": "^3.0.2" + } +} diff --git a/src/libMPC/node_modules/wif/node_modules/bs58check/LICENSE b/src/libMPC/node_modules/wif/node_modules/bs58check/LICENSE new file mode 100644 index 0000000..5dd5d5a --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58check/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Daniel Cousens + +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. diff --git a/src/libMPC/node_modules/wif/node_modules/bs58check/README.md b/src/libMPC/node_modules/wif/node_modules/bs58check/README.md new file mode 100644 index 0000000..f6f7305 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58check/README.md @@ -0,0 +1,27 @@ +# bs58check + +[![NPM Package](https://img.shields.io/npm/v/bs58check.svg?style=flat-square)](https://www.npmjs.org/package/bs58check) +[![Build Status](https://img.shields.io/travis/bitcoinjs/bs58check.svg?branch=master&style=flat-square)](https://travis-ci.org/bitcoinjs/bs58check) +[![Dependency status](https://img.shields.io/david/bitcoinjs/bs58check.svg?style=flat-square)](https://david-dm.org/bitcoinjs/bs58check#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A straight forward implementation of base58check extending upon bs58. + + +## Example + +```javascript +var bs58check = require('bs58check') + +var decoded = bs58check.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') + +console.log(decoded) +// => + +console.log(bs58check.encode(decoded)) +// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr +``` + + +## LICENSE [MIT](LICENSE) diff --git a/src/libMPC/node_modules/wif/node_modules/bs58check/base.js b/src/libMPC/node_modules/wif/node_modules/bs58check/base.js new file mode 100644 index 0000000..c9a5cd8 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58check/base.js @@ -0,0 +1,50 @@ +'use strict' + +var base58 = require('bs58') +var Buffer = require('safe-buffer').Buffer + +module.exports = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload) + + return base58.encode(Buffer.concat([ + payload, + checksum + ], payload.length + 4)) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4) + var checksum = buffer.slice(-4) + var newChecksum = checksumFn(payload) + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string) + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string) + var payload = decodeRaw(buffer, checksumFn) + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } +} diff --git a/src/libMPC/node_modules/wif/node_modules/bs58check/index.js b/src/libMPC/node_modules/wif/node_modules/bs58check/index.js new file mode 100644 index 0000000..347efec --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58check/index.js @@ -0,0 +1,12 @@ +'use strict' + +var createHash = require('create-hash') +var bs58checkBase = require('./base') + +// SHA256(SHA256(buffer)) +function sha256x2 (buffer) { + var tmp = createHash('sha256').update(buffer).digest() + return createHash('sha256').update(tmp).digest() +} + +module.exports = bs58checkBase(sha256x2) diff --git a/src/libMPC/node_modules/wif/node_modules/bs58check/package.json b/src/libMPC/node_modules/wif/node_modules/bs58check/package.json new file mode 100644 index 0000000..e57f6f0 --- /dev/null +++ b/src/libMPC/node_modules/wif/node_modules/bs58check/package.json @@ -0,0 +1,52 @@ +{ + "name": "bs58check", + "version": "2.1.2", + "description": "A straightforward implementation of base58-check encoding", + "keywords": [ + "base", + "base58", + "base58check", + "bitcoin", + "bs58", + "check", + "checksum", + "decode", + "decoding", + "encode", + "encoding", + "litecoin" + ], + "homepage": "https://github.com/bitcoinjs/bs58check", + "bugs": { + "url": "https://github.com/bitcoinjs/bs58check/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "files": [ + "index.js", + "base.js" + ], + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/bs58check.git" + }, + "scripts": { + "coverage-report": "nyc report --reporter=lcov", + "coverage": "nyc --check-coverage --branches 90 --functions 90 npm run unit", + "standard": "standard", + "test": "npm run standard && npm run coverage", + "unit": "tape test/*.js" + }, + "dependencies": { + "bs58": "^4.0.0", + "create-hash": "^1.1.0", + "safe-buffer": "^5.1.2" + }, + "devDependencies": { + "blake-hash": "^1.0.0", + "nyc": "^11.3.0", + "standard": "^10.0.3", + "tape": "^4.6.2" + } +} diff --git a/src/libMPC/node_modules/wif/package.json b/src/libMPC/node_modules/wif/package.json new file mode 100644 index 0000000..5187a95 --- /dev/null +++ b/src/libMPC/node_modules/wif/package.json @@ -0,0 +1,43 @@ +{ + "name": "wif", + "version": "2.0.6", + "description": "Bitcoin Wallet Import Format (WIF) decoding/encoding module", + "author": "Daniel Cousens", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/bitcoinjs/wif.git" + }, + "bugs": { + "url": "https://github.com/bitcoinjs/wif/issues" + }, + "homepage": "https://github.com/bitcoinjs/wif", + "keywords": [ + "bitcoin", + "base58", + "base58check", + "decode", + "decoding", + "encoding", + "encode", + "key", + "private", + "wif" + ], + "main": "index.js", + "scripts": { + "coverage-report": "nyc report --reporter=lcov", + "coverage": "nyc --check-coverage --branches 90 --functions 90 npm run unit", + "standard": "standard", + "test": "npm run standard && npm run coverage", + "unit": "tape test/*.js" + }, + "dependencies": { + "bs58check": "<3.0.0" + }, + "devDependencies": { + "nyc": "^6.4.0", + "standard": "*", + "tape": "^4.6.2" + } +} diff --git a/src/libMPC/node_modules/wif/test/fixtures.json b/src/libMPC/node_modules/wif/test/fixtures.json new file mode 100644 index 0000000..de7946c --- /dev/null +++ b/src/libMPC/node_modules/wif/test/fixtures.json @@ -0,0 +1,76 @@ +{ + "valid": [ + { + "WIF": "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn", + "compressed": true, + "privateKeyHex": "0000000000000000000000000000000000000000000000000000000000000001", + "version": 128 + }, + { + "WIF": "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf", + "compressed": false, + "privateKeyHex": "0000000000000000000000000000000000000000000000000000000000000001", + "version": 128 + }, + { + "WIF": "KxhEDBQyyEFymvfJD96q8stMbJMbZUb6D1PmXqBWZDU2WvbvVs9o", + "compressed": true, + "privateKeyHex": "2bfe58ab6d9fd575bdc3a624e4825dd2b375d64ac033fbc46ea79dbab4f69a3e", + "version": 128 + }, + { + "WIF": "KzrA86mCVMGWnLGBQu9yzQa32qbxb5dvSK4XhyjjGAWSBKYX4rHx", + "compressed": true, + "privateKeyHex": "6c4313b03f2e7324d75e642f0ab81b734b724e13fec930f309e222470236d66b", + "version": 128 + }, + { + "WIF": "5JdxzLtFPHNe7CAL8EBC6krdFv9pwPoRo4e3syMZEQT9srmK8hh", + "compressed": false, + "privateKeyHex": "6c4313b03f2e7324d75e642f0ab81b734b724e13fec930f309e222470236d66b", + "version": 128 + }, + { + "WIF": "cRD9b1m3vQxmwmjSoJy7Mj56f4uNFXjcWMCzpQCEmHASS4edEwXv", + "compressed": true, + "privateKeyHex": "6c4313b03f2e7324d75e642f0ab81b734b724e13fec930f309e222470236d66b", + "version": 239 + }, + { + "WIF": "92Qba5hnyWSn5Ffcka56yMQauaWY6ZLd91Vzxbi4a9CCetaHtYj", + "compressed": false, + "privateKeyHex": "6c4313b03f2e7324d75e642f0ab81b734b724e13fec930f309e222470236d66b", + "version": 239 + }, + { + "WIF": "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9", + "compressed": true, + "privateKeyHex": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", + "version": 128 + } + ], + "invalid": { + "decode": [ + { + "exception": "Invalid network version", + "version": 128, + "WIF": "92Qba5hnyWSn5Ffcka56yMQauaWY6ZLd91Vzxbi4a9CCetaHtYj" + }, + { + "exception": "Invalid compression flag", + "version": 128, + "WIF": "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sfZr2ym" + }, + { + "exception": "Invalid WIF length", + "version": 128, + "WIF": "3tq8Vmhh9SN5XhjTGSWgx8iKk59XbKG6UH4oqpejRuJhfYD" + }, + { + "exception": "Invalid WIF length", + "version": 128, + "WIF": "38uMpGARR2BJy5p4dNFKYg9UsWNoBtkpbdrXDjmfvz8krCtw3T1W92ZDSR" + } + ] + } +} diff --git a/src/libMPC/node_modules/wif/test/index.js b/src/libMPC/node_modules/wif/test/index.js new file mode 100644 index 0000000..d10f9a1 --- /dev/null +++ b/src/libMPC/node_modules/wif/test/index.js @@ -0,0 +1,42 @@ +var wif = require('../') +var fixtures = require('./fixtures') +var tape = require('tape') + +fixtures.valid.forEach(function (f) { + tape('encode/encodeRaw returns ' + f.WIF + ' for ' + f.privateKeyHex.slice(0, 20) + '... (' + f.version + ')', function (t) { + t.plan(1) + + var privateKey = new Buffer(f.privateKeyHex, 'hex') + var actual = wif.encode(f.version, privateKey, f.compressed) + t.equal(actual, f.WIF) + }) +}) + +fixtures.valid.forEach(function (f) { + tape('decode/decodeRaw returns ' + f.privateKeyHex.slice(0, 20) + '... (' + f.version + ')' + ' for ' + f.WIF, function (t) { + t.plan(3) + + var actual = wif.decode(f.WIF, f.version) + t.equal(actual.version, f.version) + t.equal(actual.privateKey.toString('hex'), f.privateKeyHex) + t.equal(actual.compressed, f.compressed) + }) +}) + +fixtures.invalid.decode.forEach(function (f) { + tape('throws ' + f.exception + ' for ' + f.WIF, function (t) { + t.plan(1) + t.throws(function () { + wif.decode(f.WIF, f.version) + }, new RegExp(f.exception)) + }) +}) + +fixtures.valid.forEach(function (f) { + tape('decode/encode for ' + f.WIF, function (t) { + t.plan(1) + + var actual = wif.encode(wif.decode(f.WIF, f.version)) + t.equal(actual, f.WIF) + }) +}) diff --git a/src/libMPC/package-lock.json b/src/libMPC/package-lock.json new file mode 100644 index 0000000..7cce37f --- /dev/null +++ b/src/libMPC/package-lock.json @@ -0,0 +1,460 @@ +{ + "name": "libMPC", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@noble/curves": "^1.6.0", + "@noble/secp256k1": "^2.1.0", + "bitcoinjs-lib": "^7.0.0-rc.0", + "ecpair": "^2.0.0", + "node-fetch": "^3.3.2", + "tiny-secp256k1": "^2.2.3" + } + }, + "node_modules/@noble/curves": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.6.0.tgz", + "integrity": "sha512-TlaHRXDehJuRNR9TfZDNQ45mMEd5dwUwmicsafcIX4SsNiqnCHKjE/1alYPd/lDRVhxdhUAlv8uEhMCI5zjIJQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.5.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.5.0.tgz", + "integrity": "sha512-1j6kQFb7QRru7eKN3ZDvRcP13rugwdxZqCjbiAVZfIJwgj2A65UmT4TgARXGlXgnRkORLTDTrO19ZErt7+QXgA==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/secp256k1": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-2.1.0.tgz", + "integrity": "sha512-XLEQQNdablO0XZOIniFQimiXsZDNwaYgL96dZwC54Q30imSbAOFf3NKtepc+cXyuZf5Q1HCgbqgZ2UFFuHVcEw==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/base-x": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.0.tgz", + "integrity": "sha512-sMW3VGSX1QWVFA6l8U62MLKz29rRfpTlYdCqLdpLo1/Yd4zZwSbnUaDfciIAowAqvq7YFnWq9hrhdg1KYgc1lQ==", + "license": "MIT" + }, + "node_modules/bech32": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bech32/-/bech32-2.0.0.tgz", + "integrity": "sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==", + "license": "MIT" + }, + "node_modules/bip174": { + "version": "3.0.0-rc.1", + "resolved": "https://registry.npmjs.org/bip174/-/bip174-3.0.0-rc.1.tgz", + "integrity": "sha512-+8P3BpSairVNF2Nee6Ksdc1etIjWjBOi/MH0MwKtq9YaYp+S2Hk2uvup0e8hCT4IKlS58nXJyyQVmW92zPoD4Q==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.9", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bitcoinjs-lib": { + "version": "7.0.0-rc.0", + "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-7.0.0-rc.0.tgz", + "integrity": "sha512-7CQgOIbREemKR/NT2uc3uO/fkEy+6CM0sLxboVVY6bv6DbZmPt3gg5Y/hhWgQFeZu5lfTbtVAv32MIxf7lMh4g==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bech32": "^2.0.0", + "bip174": "^3.0.0-rc.0", + "bs58check": "^4.0.0", + "uint8array-tools": "^0.0.9", + "valibot": "^0.38.0", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "dependencies": { + "base-x": "^5.0.0" + } + }, + "node_modules/bs58check": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-4.0.0.tgz", + "integrity": "sha512-FsGDOnFg9aVI9erdriULkd/JjEWONV/lQE5aYziB5PoBsXRind56lh8doIZIc9X4HoxT5x4bLjMWN1/NB8Zp5g==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bs58": "^6.0.0" + } + }, + "node_modules/cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ecpair": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ecpair/-/ecpair-2.0.0.tgz", + "integrity": "sha512-5vpYFWxq9V3r/FO33k7SHA1Tl0e4Y5qJiQ3wYGl54o3a7zflNV2U/a5dh8Wmzk5qc3g1OsDPdqBGwRmomvJxoA==", + "license": "MIT", + "dependencies": { + "randombytes": "^2.1.0", + "typeforce": "^1.18.0", + "wif": "^2.0.6" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/hash-base": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", + "integrity": "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "safe-buffer": "^5.2.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "license": "(MIT AND BSD-3-Clause)", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/tiny-secp256k1": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/tiny-secp256k1/-/tiny-secp256k1-2.2.3.tgz", + "integrity": "sha512-SGcL07SxcPN2nGKHTCvRMkQLYPSoeFcvArUSCYtjVARiFAWU44cCIqYS0mYAU6nY7XfvwURuTIGo2Omt3ZQr0Q==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "0.0.7" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tiny-secp256k1/node_modules/uint8array-tools": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.7.tgz", + "integrity": "sha512-vrrNZJiusLWoFWBqz5Y5KMCgP9W9hnjZHzZiZRT8oNAkq3d5Z5Oe76jAvVVSRh4U8GGR90N2X1dWtrhvx6L8UQ==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typeforce": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/typeforce/-/typeforce-1.18.0.tgz", + "integrity": "sha512-7uc1O8h1M1g0rArakJdf0uLRSSgFcYexrVoKo+bzJd32gd4gDy2L/Z+8/FjPnU9ydY3pEnVPtr9FyscYY60K1g==", + "license": "MIT" + }, + "node_modules/uint8array-tools": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.9.tgz", + "integrity": "sha512-9vqDWmoSXOoi+K14zNaf6LBV51Q8MayF0/IiQs3GlygIKUYtog603e6virExkjjFosfJUBI4LhbQK1iq8IG11A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/valibot": { + "version": "0.38.0", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-0.38.0.tgz", + "integrity": "sha512-RCJa0fetnzp+h+KN9BdgYOgtsMAG9bfoJ9JSjIhFHobKWVWyzM3jjaeNTdpFK9tQtf3q1sguXeERJ/LcmdFE7w==", + "license": "MIT", + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/varuint-bitcoin": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/varuint-bitcoin/-/varuint-bitcoin-2.0.0.tgz", + "integrity": "sha512-6QZbU/rHO2ZQYpWFDALCDSRsXbAs1VOEmXAxtbtjLtKuMJ/FQ8YbhfxlaiKv5nklci0M6lZtlZyxo9Q+qNnyog==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.8" + } + }, + "node_modules/varuint-bitcoin/node_modules/uint8array-tools": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.8.tgz", + "integrity": "sha512-xS6+s8e0Xbx++5/0L+yyexukU7pz//Yg6IHg3BKhXotg1JcYtgxVcUctQ0HxLByiJzpAkNFawz1Nz5Xadzo82g==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/wif": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/wif/-/wif-2.0.6.tgz", + "integrity": "sha512-HIanZn1zmduSF+BQhkE+YXIbEiH0xPr1012QbFEGB0xsKqJii0/SqJjyn8dFv6y36kOznMgMB+LGcbZTJ1xACQ==", + "license": "MIT", + "dependencies": { + "bs58check": "<3.0.0" + } + }, + "node_modules/wif/node_modules/base-x": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.10.tgz", + "integrity": "sha512-7d0s06rR9rYaIWHkpfLIFICM/tkSVdoPC9qYAQRpxn9DdKNWNsKC0uk++akckyLq16Tx2WIinnZ6WRriAt6njQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/wif/node_modules/bs58": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz", + "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==", + "license": "MIT", + "dependencies": { + "base-x": "^3.0.2" + } + }, + "node_modules/wif/node_modules/bs58check": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-2.1.2.tgz", + "integrity": "sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==", + "license": "MIT", + "dependencies": { + "bs58": "^4.0.0", + "create-hash": "^1.1.0", + "safe-buffer": "^5.1.2" + } + } + } +} diff --git a/src/libMPC/package.json b/src/libMPC/package.json new file mode 100644 index 0000000..0e01052 --- /dev/null +++ b/src/libMPC/package.json @@ -0,0 +1,10 @@ +{ + "dependencies": { + "@noble/curves": "^1.6.0", + "@noble/secp256k1": "^2.1.0", + "bitcoinjs-lib": "^7.0.0-rc.0", + "ecpair": "^2.0.0", + "node-fetch": "^3.3.2", + "tiny-secp256k1": "^2.2.3" + } +} diff --git a/src/libMPC/rfc8032.mjs b/src/libMPC/rfc8032.mjs new file mode 100644 index 0000000..4436c37 --- /dev/null +++ b/src/libMPC/rfc8032.mjs @@ -0,0 +1,12 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/********************************************************************************************/ + diff --git a/src/libMPC/test_Musig2.mjs b/src/libMPC/test_Musig2.mjs new file mode 100644 index 0000000..34ce51c --- /dev/null +++ b/src/libMPC/test_Musig2.mjs @@ -0,0 +1,296 @@ +/********************************************************************************************/ +/* +/* ___ _ _ ___ _ _ _ _ +/* / __|_ __ ___ ___| |_| |_ / __|_ _ _ _ _ __| |_ ___ | | (_) |__ +/* \__ \ ' \/ _ \/ _ \ _| ' \ | (__| '_| || | '_ \ _/ _ \ | |__| | '_ \ +/* |___/_|_|_\___/\___/\__|_||_| \___|_| \_, | .__/\__\___/ |____|_|_.__/ +/* |__/|_| +/* +/* Copyright (C) 2024 - Renaud Dubois - This file is part of SCL (Smooth CryptoLib) project +/* License: This software is licensed under MIT License +/********************************************************************************************/ + + +import{SCL_ecc} from './SCL_ecc.mjs'; +import{SCL_Musig2} from './SCL_Musig2.mjs'; + + +function test_compression(){ + console.log("/*************************** "); + console.log("Test compression/decompression"); + + const curve = 'ed25519'; + const signer = new SCL_ecc(curve); + + + let Point=signer.GetBase(); + + let cP=signer.PointCompress(Point); + let rP=signer.PointDecompress(cP); + + console.log(":", rP.equals(Point)); +} + +function test_keyaggcoeff(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Test key_agg:"); + + + let pubkeys=[ + Buffer.from("02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9",'hex'), + Buffer.from("03DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",'hex'), + Buffer.from("023590A94E768F8E1815C2F24B4D80A8E3149316C3518CE7B7AD338368D038CA66",'hex') + ]; + + let expected=Buffer.from("0290539EEDE565F5D054F32CC0C220126889ED1E5D193BAF15AEF344FE59D4610C",'hex'); + + let aggpk=(signer.Key_agg(pubkeys)[0]) + console.log(":", Buffer.from(aggpk).equals(expected));//check key aggregation is correct + + return Buffer.from(aggpk).equals(expected); +} + + +function test_noncegen(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Test nonce_gen_internal:"); + + //extracted from https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/nonce_gen_vectors.json + const rand= [ + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F" + ]; + + const sk= [ + "0202020202020202020202020202020202020202020202020202020202020202", + "0202020202020202020202020202020202020202020202020202020202020202", + "0202020202020202020202020202020202020202020202020202020202020202", + "" + ]; + + const pk= [ + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9" + ]; + + const + aggpk= [ + "0707070707070707070707070707070707070707070707070707070707070707", + "0707070707070707070707070707070707070707070707070707070707070707", + "0707070707070707070707070707070707070707070707070707070707070707", + "" + ]; + + const msg= [ + "0101010101010101010101010101010101010101010101010101010101010101", + "", + "2626262626262626262626262626262626262626262626262626262626262626262626262626", + "" + ]; + + const extra_in= [ + "0808080808080808080808080808080808080808080808080808080808080808", + "0808080808080808080808080808080808080808080808080808080808080808", + "0808080808080808080808080808080808080808080808080808080808080808", + "" + ]; + + const expected_secnonce= [ + "B114E502BEAA4E301DD08A50264172C84E41650E6CB726B410C0694D59EFFB6495B5CAF28D045B973D63E3C99A44B807BDE375FD6CB39E46DC4A511708D0E9D2024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "E862B068500320088138468D47E0E6F147E01B6024244AE45EAC40ACE5929B9F0789E051170B9E705D0B9EB49049A323BBBBB206D8E05C19F46C6228742AA7A9024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "3221975ACBDEA6820EABF02A02B7F27D3A8EF68EE42787B88CBEFD9AA06AF3632EE85B1A61D8EF31126D4663A00DD96E9D1D4959E72D70FE5EBB6E7696EBA66F024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "89BDD787D0284E5E4D5FC572E49E316BAB7E21E3B1830DE37DFE80156FA41A6D0B17AE8D024C53679699A6FD7944D9C4A366B514BAF43088E0708B1023DD289702F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9" + ]; + + const expected_pubnonce= [ + "02F7BE7089E8376EB355272368766B17E88E7DB72047D05E56AA881EA52B3B35DF02C29C8046FDD0DED4C7E55869137200FBDBFE2EB654267B6D7013602CAED3115A", + "023034FA5E2679F01EE66E12225882A7A48CC66719B1B9D3B6C4DBD743EFEDA2C503F3FD6F01EB3A8E9CB315D73F1F3D287CAFBB44AB321153C6287F407600205109", + "02E5BBC21C69270F59BD634FCBFA281BE9D76601295345112C58954625BF23793A021307511C79F95D38ACACFF1B4DA98228B77E65AA216AD075E9673286EFB4EAF3", + "02C96E7CB1E8AA5DAC64D872947914198F607D90ECDE5200DE52978AD5DED63C000299EC5117C2D29EDEE8A2092587C3909BE694D5CFF0667D6C02EA4059F7CD9786" + ]; + + for( var i=0;i<1;i++) + { + let i_rand=Buffer.from(rand[i],'hex'); + console.log("rand noncegen=", i_rand); + let i_pk=Buffer.from(pk[i],'hex'); + let i_sk=Buffer.from(sk[i],'hex'); + + let i_aggpk=Buffer.from(aggpk[i],'hex'); + let i_extra=Buffer.from(extra_in[i],'hex'); + let i_msg=Buffer.from(msg[i],'hex'); + + let res=signer.Nonce_hash(i_rand, i_pk, i_aggpk, 0, signer.prefix_msg(i_msg), i_extra); + res=res.equals(Buffer.from("bf2dca60c7ca80ffe6bf4e7c75982611f24ad6946cc8be6f0eebe67d186799ca", 'hex')); + if(res==false) return false; + + res=signer.Nonce_gen_internal(i_rand, i_sk, i_pk, i_aggpk, i_msg, i_extra); + + + if((res[0]).equals(Buffer.from(expected_secnonce[i],'hex'))==false) return false; + if((res[1]).equals(Buffer.from(expected_pubnonce[i],'hex'))==false) return false; + + } + + console.log("\n result:", true ); + + return true; + } + +function test_nonceagg(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Test nonce_agg:"); + + + //partial public nonces before aggregation + let pnonces= [ + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E66603BA47FBC1834437B3212E89A84D8425E7BF12E0245D98262268EBDCB385D50641", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60248C264CDD57D3C24D79990B0F865674EB62A0F9018277A95011B41BFC193B833", + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E6660279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60379BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + ]; + + let expected_agg1="035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B024725377345BDE0E9C33AF3C43C0A29A9249F2F2956FA8CFEB55C8573D0262DC8"; + let expected_agg2="035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B000000000000000000000000000000000000000000000000000000000000000000"; + + + let res=signer.Nonce_agg([pnonces[0], pnonces[1]]); + + + + console.log(res.equals(Buffer.from(expected_agg1,'hex'))); + res=signer.Nonce_agg([pnonces[2], pnonces[3]]); + + console.log(res.equals(Buffer.from(expected_agg2,'hex'))); + + + } + + +//valid test case 3, https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/sig_agg_vectors.json +function test_partialsig_withtweak_1(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Test signature aggregation:"); + + const msg=Buffer.from("599C67EA410D005B9DA90817CF03ED3B1C868E4DA4EDF00A5880B0082C237869", 'hex'); + + + const aggnonce=Buffer.from("0208C5C438C710F4F96A61E9FF3C37758814B8C3AE12BFEA0ED2C87FF6954FF186020B1816EA104B4FCA2D304D733E0E19CEAD51303FF6420BFD222335CAA402916D", 'hex'); + + const pubkeys=[Buffer.from("03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", 'hex'), + Buffer.from("03C7FB101D97FF930ACD0C6760852EF64E69083DE0B06AC6335724754BB4B0522C", 'hex')]; + + const tweaks=[Buffer.from("B511DA492182A91B0FFB9A98020D55F260AE86D7ECBD0399C7383D59A5F2AF7C", 'hex')]; + + const psigs=[Buffer.from("4F5AEE41510848A6447DCD1BBC78457EF69024944C87F40250D3EF2C25D33EFE", 'hex'), + Buffer.from("DDEF427BBB847CC027BEFF4EDB01038148917832253EBC355FC33F4A8E2FCCE4", 'hex')]; + + const expected="5C558E1DCADE86DA0B2F02626A512E30A22CF5255CAEA7EE32C38E9A71A0E9148BA6C0E6EC7683B64220F0298696F1B878CD47B107B81F7188812D593971E0CC"; + + const session_context=[aggnonce, pubkeys, tweaks, [false], msg ]; + + + let res=signer.Partial_sig_agg(psigs, session_context); + + console.log("", Buffer.from(expected,'hex').equals(res)); + } + + +//a full session generated using reference.py +function unitary_fullsession(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Full session, compare with python generated input:"); + + const msg=Buffer.from("e0601e248a22338872c707bdd7627195e4ea56ac9ad4c4c900560b8f39ad1dab", 'hex'); + + const sk1=Buffer.from("a35de7d4e30dc61b6eadd376c2e62072f2be817b6468d3021e2a443762d396bd", 'hex'); + const pubK1=signer.IndividualPubKey_array(sk1); + const sk2=Buffer.from("cbdee7c9611746164315d955f75234778dddaa3e50f220283f3deb0dafe20dab", 'hex'); + const pubK2=signer.IndividualPubKey_array(sk2); + + const pubkeys=[pubK1, pubK2]; + + let aggpk = signer.Key_agg(pubkeys)[0];//here aggpk is a 33 bytes compressed public key + let x_aggpk=aggpk.slice(1,33);//x-only version for noncegen + + console.log("Aggregated Pubkey:", aggpk); + + const rand1=Buffer.from("0cea0923038e6fa408e728539dca5accb1f9d433150f0d2680607afe831955bd", 'hex'); + const rand2=Buffer.from("cb555086ba1e545c0fef5bc4c35bb6e1fec90a482a4bfc20e10896c372e78661", 'hex'); + + const nonce1=signer.Nonce_gen_internal(rand1, sk1, pubK1, x_aggpk, msg, Buffer.from("00000000", 'hex')); + const nonce2=signer.Nonce_gen_internal(rand2, sk2, pubK2, x_aggpk, msg, Buffer.from("00000000", 'hex')); + + let aggnonce = signer.Nonce_agg([nonce1[1].toString('hex'), nonce2[1].toString('hex')]); + console.log("aggnonce is =", aggnonce); + + + //'aggnonce','pubkeys', 'tweaks', 'is_xonly','msg'; + const session_ctx=[aggnonce, pubkeys, [], [], msg]; + + let p1=signer.Psign(nonce1[0], sk1, session_ctx); + console.log("p1=",p1); + + + let p2=signer.Psign(nonce2[0], sk2, session_ctx); + console.log("p2=",p2); + + let psigs=[p1,p2]; + + let res=signer.Partial_sig_agg(psigs, session_ctx); + console.log("res=", res, res.length); + + let check=signer.Schnorr_verify(msg, x_aggpk, res); + + console.log("check=", check); + } + + + +function test_schnorrverify(){ + const curve = 'secp256k1'; + const signer = new SCL_Musig2(curve); + + console.log("/*************************** "); + console.log("Test Schnorr_verify:"); +let msg= Buffer.from("28d5dd7459fc54ff02304280ce9bcc54a29cf0e5d72cd4ccafe961a1cfe8a8d3",'hex'); +let aggpk=Buffer.from("23189cc577a55b5ba8016136947cb0a1e97567d332cc993e9d108010708f10c0",'hex'); +let sig=Buffer.from("61074a45b0030ff5b7280dd094bf06c361adc0394a9bd17756db7bc9aa5983536c5b2ebc4404cf1f04e71c3795484fe83aabc48845a56f796d7c816a67601256",'hex'); + +//0x61074a45b0030ff5b7280dd094bf06c361adc0394a9bd17756db7bc9aa59835323189cc577a55b5ba8016136947cb0a1e97567d332cc993e9d108010708f10c028d5dd7459fc54ff02304280ce9bcc54a29cf0e5d72cd4ccafe961a1cfe8a8d3 +//e=0x833cad5d5e04b2edc3fac1cba4b921c6bf4404c0c6dd40af44be6395e53b2504 + let res=signer.Schnorr_verify(msg, aggpk, sig); + + console.log("", res); +} + +(async () => { + + + test_compression(); + test_keyaggcoeff();//key aggregation is ok + test_noncegen(); + test_nonceagg(); + test_partialsig_withtweak_1(); + test_schnorrverify(); + unitary_fullsession(); +})(); \ No newline at end of file diff --git a/src/libMPC/test_bip327.mjs b/src/libMPC/test_bip327.mjs new file mode 100644 index 0000000..0b4db0a --- /dev/null +++ b/src/libMPC/test_bip327.mjs @@ -0,0 +1,450 @@ +import{IndividualPubKey_array, psign, partial_sig_agg, schnorr_verify, sha256, tagged_hashBTC, prefix_msg, nonce_gen_internal, nonce_hash, nonce_agg, hash_keys, key_agg_coeff, int_from_bytes, key_agg, nonce_gen} from './bip327.mjs' + +import { randomBytes } from 'crypto'; // Use Node.js's crypto module +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js + + + +/********************************************************************************************/ +/* SESSION EXAMPLE*/ +/********************************************************************************************/ +function test_noncegen(){ + + console.log("/*************************** "); + console.log("Test nonce_gen_internal:"); + + //extracted from https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/nonce_gen_vectors.json + const rand= [ + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F" + ]; + + const sk= [ + "0202020202020202020202020202020202020202020202020202020202020202", + "0202020202020202020202020202020202020202020202020202020202020202", + "0202020202020202020202020202020202020202020202020202020202020202", + "" + ]; + + const pk= [ + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9" + ]; + + const + aggpk= [ + "0707070707070707070707070707070707070707070707070707070707070707", + "0707070707070707070707070707070707070707070707070707070707070707", + "0707070707070707070707070707070707070707070707070707070707070707", + "" + ]; + + const msg= [ + "0101010101010101010101010101010101010101010101010101010101010101", + "", + "2626262626262626262626262626262626262626262626262626262626262626262626262626", + "" + ]; + + const extra_in= [ + "0808080808080808080808080808080808080808080808080808080808080808", + "0808080808080808080808080808080808080808080808080808080808080808", + "0808080808080808080808080808080808080808080808080808080808080808", + "" + ]; + + const expected_secnonce= [ + "B114E502BEAA4E301DD08A50264172C84E41650E6CB726B410C0694D59EFFB6495B5CAF28D045B973D63E3C99A44B807BDE375FD6CB39E46DC4A511708D0E9D2024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "E862B068500320088138468D47E0E6F147E01B6024244AE45EAC40ACE5929B9F0789E051170B9E705D0B9EB49049A323BBBBB206D8E05C19F46C6228742AA7A9024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "3221975ACBDEA6820EABF02A02B7F27D3A8EF68EE42787B88CBEFD9AA06AF3632EE85B1A61D8EF31126D4663A00DD96E9D1D4959E72D70FE5EBB6E7696EBA66F024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "89BDD787D0284E5E4D5FC572E49E316BAB7E21E3B1830DE37DFE80156FA41A6D0B17AE8D024C53679699A6FD7944D9C4A366B514BAF43088E0708B1023DD289702F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9" + ]; + + const expected_pubnonce= [ + "02F7BE7089E8376EB355272368766B17E88E7DB72047D05E56AA881EA52B3B35DF02C29C8046FDD0DED4C7E55869137200FBDBFE2EB654267B6D7013602CAED3115A", + "023034FA5E2679F01EE66E12225882A7A48CC66719B1B9D3B6C4DBD743EFEDA2C503F3FD6F01EB3A8E9CB315D73F1F3D287CAFBB44AB321153C6287F407600205109", + "02E5BBC21C69270F59BD634FCBFA281BE9D76601295345112C58954625BF23793A021307511C79F95D38ACACFF1B4DA98228B77E65AA216AD075E9673286EFB4EAF3", + "02C96E7CB1E8AA5DAC64D872947914198F607D90ECDE5200DE52978AD5DED63C000299EC5117C2D29EDEE8A2092587C3909BE694D5CFF0667D6C02EA4059F7CD9786" + ]; + + for( var i=0;i<1;i++) + { + let i_rand=Buffer.from(rand[i],'hex'); + console.log("rand noncegen=", i_rand); + let i_pk=Buffer.from(pk[i],'hex'); + let i_sk=Buffer.from(sk[i],'hex'); + + let i_aggpk=Buffer.from(aggpk[i],'hex'); + let i_extra=Buffer.from(extra_in[i],'hex'); + let i_msg=Buffer.from(msg[i],'hex'); + + let res=nonce_hash(i_rand, i_pk, i_aggpk, 0, prefix_msg(i_msg), i_extra); + res=res.equals(Buffer.from("bf2dca60c7ca80ffe6bf4e7c75982611f24ad6946cc8be6f0eebe67d186799ca", 'hex')); + if(res==false) return false; + + res=nonce_gen_internal(i_rand, i_sk, i_pk, i_aggpk, i_msg, i_extra); + + + if((res[0]).equals(Buffer.from(expected_secnonce[i],'hex'))==false) return false; + if((res[1]).equals(Buffer.from(expected_pubnonce[i],'hex'))==false) return false; + + } + + console.log("\n result:", true ); + + return true; + } + +function test_tagged_hashBTC(){ + console.log("/*************************** JAVASCRIPT BIP 327 TESTS ********************************/" ); + + console.log("/*************************** "); + + console.log("Test tagged_hashBTC:"); + + const tag = "BIP0340/challenge"; + const tagHash = sha256(Buffer.from(tag, 'utf-8')); + const message = Buffer.from("abc", 'utf-8'); + const result = tagged_hashBTC(tag, message); + const expected = Buffer.from("770a5b7e7c304bbcc3ea107343ff951dd404312ef418db0c3b94e2ebfbb50087",'hex'); + + console.log("message ", message); + console.log("Resulting hash", result); + console.log("expected hash", expected); + + console.log("\n result:", result.equals(expected) ) + return (result.equals(expected)); + } + +function test_nonceagg(){ + console.log("/*************************** "); + console.log("Test nonce_agg:"); + + + //partial public nonces before aggregation + let pnonces= [ + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E66603BA47FBC1834437B3212E89A84D8425E7BF12E0245D98262268EBDCB385D50641", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60248C264CDD57D3C24D79990B0F865674EB62A0F9018277A95011B41BFC193B833", + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E6660279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60379BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + ]; + + let expected_agg1="035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B024725377345BDE0E9C33AF3C43C0A29A9249F2F2956FA8CFEB55C8573D0262DC8"; + let expected_agg2="035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B000000000000000000000000000000000000000000000000000000000000000000"; + + + let res=nonce_agg([pnonces[0], pnonces[1]]); + + + console.log("res",res); + console.log("expected",expected_agg1); + + console.log(res.equals(Buffer.from(expected_agg1,'hex'))); + res=nonce_agg([pnonces[2], pnonces[3]]); + + console.log(res.equals(Buffer.from(expected_agg2,'hex'))); + return 1; + console.log("res",res); + console.log("expected",expected_agg2); + +} + +function test_keyaggcoeff(){ + console.log("/*************************** "); + console.log("Test key_agg:"); + + + let pubkeys=[ + Buffer.from("02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9",'hex'), + Buffer.from("03DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",'hex'), + Buffer.from("023590A94E768F8E1815C2F24B4D80A8E3149316C3518CE7B7AD338368D038CA66",'hex') + ]; + + let res=hash_keys(pubkeys); + let expected_h="9d3ba89d01849c97649989f2a441f701be800aaa15d957e687d4f56479bc49b9"; + + console.log("hashkeys", res, expected_h); + res=key_agg_coeff(pubkeys, pubkeys[0]); + let expected= int_from_bytes(Buffer.from("ad0537c883813849e3b95ce5db1d45eb25cc5fae197c4e8759719065932aa183",'hex')); + + console.log("key agg coeff 0", res.toString(16), expected.toString(16));//test first coefficient is correct + + console.log("test 1:", expected==res); + + expected=Buffer.from("90539EEDE565F5D054F32CC0C220126889ED1E5D193BAF15AEF344FE59D4610C",'hex'); + + let aggpk=(key_agg(pubkeys)[0]).slice(1,33); + console.log("test 2::", Buffer.from(aggpk).equals(expected));//check key aggregation is correct + +} + + +function test_schnorrverify(){ + console.log("/*************************** "); + console.log("Test chnorr_verify:"); +let msg= Buffer.from("28d5dd7459fc54ff02304280ce9bcc54a29cf0e5d72cd4ccafe961a1cfe8a8d3",'hex'); +let aggpk=Buffer.from("23189cc577a55b5ba8016136947cb0a1e97567d332cc993e9d108010708f10c0",'hex'); +let sig=Buffer.from("61074a45b0030ff5b7280dd094bf06c361adc0394a9bd17756db7bc9aa5983536c5b2ebc4404cf1f04e71c3795484fe83aabc48845a56f796d7c816a67601256",'hex'); + +//0x61074a45b0030ff5b7280dd094bf06c361adc0394a9bd17756db7bc9aa59835323189cc577a55b5ba8016136947cb0a1e97567d332cc993e9d108010708f10c028d5dd7459fc54ff02304280ce9bcc54a29cf0e5d72cd4ccafe961a1cfe8a8d3 +//e=0x833cad5d5e04b2edc3fac1cba4b921c6bf4404c0c6dd40af44be6395e53b2504 + let res=schnorr_verify(msg, aggpk, sig); + + console.log("", res); +} + +//todo as comeback, sign_verify.json +function test_partialsig_notweak(){ + console.log("/*************************** "); + console.log("Partial sig no tweak:"); + + const pubkeys= [ + Buffer.from("03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", 'hex'), + Buffer.from("02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", 'hex'), + Buffer.from("02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA661", 'hex') + ]; + + const secnonce=Buffer.from( + "508B81A611F100A6B2B6B29656590898AF488BCF2E1F55CF22E5CFB84421FE61FA27FD49B1D50085B481285E1CA205D55C82CC1B31FF5CD54A489829355901F703935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9" + , 'hex'); + + const sk=Buffer.from("7FB9E0E687ADA1EEBF7ECFE2F21E73EBDB51A7D450948DFE8D76D7F2D1007671", 'hex'); + const aggnonce=Buffer.from("028465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD61037496A3CC86926D452CAFCFD55D25972CA1675D549310DE296BFF42F72EEEA8C9",'hex'); + const msg=Buffer.from("F95466D086770E689964664219266FE5ED215C92AE20BAB5C9D79ADDDDF3C0CF",'hex'); + + //'aggnonce','pubkeys', 'tweaks', 'is_xonly','msg'; + const session_ctx=[aggnonce, pubkeys, [], [], msg]; + const expected=Buffer.from("012ABBCB52B3016AC03AD82395A1A415C48B93DEF78718E62A7A90052FE224FB", 'hex'); + + let res= psign(secnonce, sk, session_ctx); + + console.log("res=", Buffer.from(res)); + + console.log("expected=", expected); + + console.log( Buffer.from(res).equals(expected)); + +} + +//valid test case 1 from https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/sig_agg_vectors.json +function test_sigagg_notweak(){ + console.log("/*************************** "); + console.log("Test signature aggregation without tweak:"); + + + const pubkeys=[Buffer.from("03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", 'hex'), + Buffer.from("02D2DC6F5DF7C56ACF38C7FA0AE7A759AE30E19B37359DFDE015872324C7EF6E05", 'hex')]; + + const tweaks=[]; + const msg=Buffer.from("599C67EA410D005B9DA90817CF03ED3B1C868E4DA4EDF00A5880B0082C237869", 'hex'); + + const psigs=[Buffer.from("B15D2CD3C3D22B04DAE438CE653F6B4ECF042F42CFDED7C41B64AAF9B4AF53FB", 'hex'), + Buffer.from("6193D6AC61B354E9105BBDC8937A3454A6D705B6D57322A5A472A02CE99FCB64", 'hex')]; + + const aggnonce=Buffer.from("0341432722C5CD0268D829C702CF0D1CBCE57033EED201FD335191385227C3210C03D377F2D258B64AADC0E16F26462323D701D286046A2EA93365656AFD9875982B", 'hex'); + const expected="041DA22223CE65C92C9A0D6C2CAC828AAF1EEE56304FEC371DDF91EBB2B9EF0912F1038025857FEDEB3FF696F8B99FA4BB2C5812F6095A2E0004EC99CE18DE1E"; + + //session context: 'aggnonce','pubkeys', 'tweaks', 'is_xonly','msg + const session_context=[aggnonce, pubkeys, tweaks, [], msg ]; + + let res=partial_sig_agg(psigs, session_context); + console.log("res=", res.toString('hex')); + + let aggpkX=key_agg(pubkeys)[0].slice(1,33); + let vrf=schnorr_verify(msg, aggpkX, res); + + console.log("schnorr verify=", vrf); + +} + + +//valid test case 3, https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/sig_agg_vectors.json +function test_partialsig_withtweak_1(){ + const msg=Buffer.from("599C67EA410D005B9DA90817CF03ED3B1C868E4DA4EDF00A5880B0082C237869", 'hex'); + + + const aggnonce=Buffer.from("0208C5C438C710F4F96A61E9FF3C37758814B8C3AE12BFEA0ED2C87FF6954FF186020B1816EA104B4FCA2D304D733E0E19CEAD51303FF6420BFD222335CAA402916D", 'hex'); + + const pubkeys=[Buffer.from("03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", 'hex'), + Buffer.from("03C7FB101D97FF930ACD0C6760852EF64E69083DE0B06AC6335724754BB4B0522C", 'hex')]; + + const tweaks=[Buffer.from("B511DA492182A91B0FFB9A98020D55F260AE86D7ECBD0399C7383D59A5F2AF7C", 'hex')]; + + const psigs=[Buffer.from("4F5AEE41510848A6447DCD1BBC78457EF69024944C87F40250D3EF2C25D33EFE", 'hex'), + Buffer.from("DDEF427BBB847CC027BEFF4EDB01038148917832253EBC355FC33F4A8E2FCCE4", 'hex')]; + + const expected="5C558E1DCADE86DA0B2F02626A512E30A22CF5255CAEA7EE32C38E9A71A0E9148BA6C0E6EC7683B64220F0298696F1B878CD47B107B81F7188812D593971E0CC"; + + const session_context=[aggnonce, pubkeys, tweaks, [false], msg ]; + + + let res=partial_sig_agg(psigs, session_context); + console.log("res=", res.toString('hex')); +} + + +//valid test case 3, https://github.com/bitcoin/bips/blob/master/bip-0327/vectors/sig_agg_vectors.json +function test_partialsig_withtweak_2(){ + const msg=Buffer.from("599C67EA410D005B9DA90817CF03ED3B1C868E4DA4EDF00A5880B0082C237869", 'hex'); + + + const aggnonce=Buffer.from("02B5AD07AFCD99B6D92CB433FBD2A28FDEB98EAE2EB09B6014EF0F8197CD58403302E8616910F9293CF692C49F351DB86B25E352901F0E237BAFDA11F1C1CEF29FFD", 'hex'); + + const pubkeys=[Buffer.from("03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", 'hex'), + Buffer.from("02352433B21E7E05D3B452B81CAE566E06D2E003ECE16D1074AABA4289E0E3D581", 'hex')]; + + const tweaks=[Buffer.from("B511DA492182A91B0FFB9A98020D55F260AE86D7ECBD0399C7383D59A5F2AF7C", 'hex'), + Buffer.from("A815FE049EE3C5AAB66310477FBC8BCCCAC2F3395F59F921C364ACD78A2F48DC", 'hex'), + Buffer.from("75448A87274B056468B977BE06EB1E9F657577B7320B0A3376EA51FD420D18A8", 'hex') + ]; + + const psigs=[Buffer.from("97B890A26C981DA8102D3BC294159D171D72810FDF7C6A691DEF02F0F7AF3FDC", 'hex'), + Buffer.from("53FA9E08BA5243CBCB0D797C5EE83BC6728E539EB76C2D0BF0F971EE4E909971", 'hex')]; + + const expected=Buffer.from("839B08820B681DBA8DAF4CC7B104E8F2638F9388F8D7A555DC17B6E6971D7426CE07BF6AB01F1DB50E4E33719295F4094572B79868E440FB3DEFD3FAC1DB589E", 'hex'); + + const session_context=[aggnonce, pubkeys, tweaks, [true, false, true], msg ]; + + + let res=partial_sig_agg(psigs, session_context); + console.log("res=", res.toString('hex'), res); + console.log(expected.equals( res)); + +} + + +//a full session generated using reference.py +function unitary_fullsession(){ + console.log("/*************************** "); + console.log("Full session, compare with python generated input:"); + + const msg=Buffer.from("e0601e248a22338872c707bdd7627195e4ea56ac9ad4c4c900560b8f39ad1dab", 'hex'); + + const sk1=Buffer.from("a35de7d4e30dc61b6eadd376c2e62072f2be817b6468d3021e2a443762d396bd", 'hex'); + const pubK1=IndividualPubKey_array(sk1); + const sk2=Buffer.from("cbdee7c9611746164315d955f75234778dddaa3e50f220283f3deb0dafe20dab", 'hex'); + const pubK2=IndividualPubKey_array(sk2); + + const pubkeys=[pubK1, pubK2]; + + let aggpk = key_agg(pubkeys)[0];//here aggpk is a 33 bytes compressed public key + let x_aggpk=aggpk.slice(1,33);//x-only version for noncegen + + console.log("Aggregated Pubkey:", aggpk); + + const rand1=Buffer.from("0cea0923038e6fa408e728539dca5accb1f9d433150f0d2680607afe831955bd", 'hex'); + const rand2=Buffer.from("cb555086ba1e545c0fef5bc4c35bb6e1fec90a482a4bfc20e10896c372e78661", 'hex'); + + const nonce1=nonce_gen_internal(rand1, sk1, pubK1, x_aggpk, msg, Buffer.from("00000000", 'hex')); + const nonce2=nonce_gen_internal(rand2, sk2, pubK2, x_aggpk, msg, Buffer.from("00000000", 'hex')); + + let aggnonce = nonce_agg([nonce1[1].toString('hex'), nonce2[1].toString('hex')]); + console.log("aggnonce is =", aggnonce); + + + //'aggnonce','pubkeys', 'tweaks', 'is_xonly','msg'; + const session_ctx=[aggnonce, pubkeys, [], [], msg]; + + let p1=psign(nonce1[0], sk1, session_ctx); + console.log("p1=",p1); + + + let p2=psign(nonce2[0], sk2, session_ctx); + console.log("p2=",p2); + + let psigs=[p1,p2]; + + let res=partial_sig_agg(psigs, session_ctx); + console.log("res=", res, res.length); + + let check=schnorr_verify(msg, x_aggpk, res); + + console.log("check=", check); +} + + +//illustrate a session without tweak, generates a new vector at each iteration +function test_sign_and_verify_random_notweak(){ + console.log("/*************************** "); + console.log("Test full session, random generation of input:"); + + + const sk1=secp256k1.utils.randomPrivateKey();//this provides a 32 bytes array + const sk2=secp256k1.utils.randomPrivateKey(); + + console.log("sk1=",sk1 ); + console.log("sk2=",sk2 ); + let seckeys=[sk1, sk2]; + + const pubK1=IndividualPubKey_array(sk1); + const pubK2=IndividualPubKey_array(sk2); + + console.log("pubK1=",pubK1 ); + console.log("pubK2=",pubK2 ); + + const pubkeys=[pubK1, pubK2]; + + let aggpk = key_agg(pubkeys)[0];//here aggpk is a 33 bytes compressed public key + let x_aggpk=aggpk.slice(1,33);//x-only version for noncegen + + console.log("Aggregated Pubkey:", aggpk); + + let msg=Buffer.from(randomBytes(32)); + let i=0; + + //diversification chain + const extra_in= Buffer.from(randomBytes(32)); + + let nonce1= nonce_gen(seckeys[0], pubkeys[0], x_aggpk, msg, extra_in); + let nonce2= nonce_gen(seckeys[1], pubkeys[1], x_aggpk, msg, extra_in); + + //aggregation of public nonces + let aggnonce = nonce_agg([nonce1[1].toString('hex'), nonce2[1].toString('hex')]); + console.log("aggnonce=", aggnonce); + + //'aggnonce','pubkeys', 'tweaks', 'is_xonly','msg'; + const session_ctx=[aggnonce, pubkeys, [], [], msg]; + + let p1=psign(nonce1[0], seckeys[0], session_ctx); + console.log("p1=",p1); + + let p2=psign(nonce2[0], seckeys[1], session_ctx); + console.log("p2=",p2); + + let psigs=[p1,p2]; + + let res=partial_sig_agg(psigs, session_ctx); + console.log("res=", res, res.length); + + let check=schnorr_verify(msg, x_aggpk, res); + + console.log("check=", check); +} + + + (async () => { + + // Example usage: + /* + test_tagged_hashBTC(); //hash is ok + test_noncegen(); //nonce generation is ok + test_nonceagg();//nonce aggregation is ok + + + test_partialsig_notweak();//partial signature is ok + + test_sigagg_notweak();//signature aggregation is ok + */ + test_keyaggcoeff();//key aggregation is ok + unitary_fullsession(); + test_sign_and_verify_random_notweak(); + + + + })(); + + \ No newline at end of file